P
P
parkito2016-04-23 11:05:04
MySQL
parkito, 2016-04-23 11:05:04

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');

Data is added keeping the tuples already in the table.
I want to do the same in Hibirnate - as a result I get the added tuple, but the rest are removed.
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!");

Can you please tell me how to organize a program to successfully add data to a table without deleting existing ones?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ruslanys, 2016-04-28
@ruslanys

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;

}

Preservation:
...
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 question

Ask a Question

731 491 924 answers to any question