Answer the question
In order to leave comments, you need to log in
How to insert data into a table in Hibernate?
Hello. Please help me solve the following problem.
I want to add data to MySQL database table. Successfully doing this with a query
INSERT INTO Students
(student_id, firstname, lastname)
VALUES
('1', 'Artyom', 'Ivanov');
Session session = Factory.getSessionFactory().openSession();
session.beginTransaction();
Query query1 = session.createSQLQuery("INSERT INTO Students\n" +
"(student_id,firstname,lastname) \n" +
"VALUES \n" +
"('3','Ivan','Ivanov');");
query1.executeUpdate();
session.getTransaction().commit();
session.close();
System.out.println("Succsess!");
Answer the question
In order to leave comments, you need to log in
Hibernate implies that you will work with objects, not with SQL queries. Ultimately, use JDBC if you want to leave the SQL option.
In Hibernate, the task will be solved like this (I want to note that according to the specification, each object must have a unique key - ID):
@Entity
@Table(name = "students")
@Data
public class Student extends BaseModel {
@Id
private Long id;
@Column
private Long studentId;
@Column
private String firstname;
@Column
private String lastname;
}
...
public Student add(Student student) {
Session session = sessionFactory.getCurrentSession();
student.setId(null); // добавить новую запись, а не изменить существующую
session.save(student);
return student;
}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question