Inserting Objects with Hibernate

In this hibernate tutorial, we will learn to insert data in the database using various techniques available through hibernate and Jakarta persistence API.

1. Setup

We have an Employee object in the application that we want to store in the database.

@Entity
@Table(name = "TBL_EMPLOYEE")
public class EmployeeEntity implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer employeeId;

  private String email;

  private String firstName;

  private String lastName;

  //Getters and setters are hidden for brevity
}

It can have more fields, but I am taking only four to make the example concrete.

2. Using Session#persist() and Session#save()

The Session interface provides many methods to perform CRUD operations on an Entity. Its persist() method will save the entity into the database.

Session session = sessionFactory.openSession();
session.beginTransaction();

EmployeeEntity emp = new EmployeeEntity();
emp.setEmail("howtodoinjava@gmail.com");
emp.setFirstName("demo");
emp.setLastName("user");

Assertions.assertNull(emp.getEmployeeId());
session.persist(emp);
Assertions.assertNotNull(emp.getEmployeeId());

session.getTransaction().commit();
session.close();

Session has another method save() that works similar to persist(). But it behaves differently for detached entities. The save() call on a detached instance creates a new persistent instance and creates a new primary key. It results in a duplicate record in the database upon committing or flushing.

EmployeeEntity emp = new EmployeeEntity();
emp.setEmail("howtodoinjava@gmail.com");
emp.setFirstName("demo");
emp.setLastName("user");

Long id1 = (Long) session.save(emp);

session.evict(emp);

Long id2 = (Long) session.save(emp);

We must configure the SessionFactory using the XML configuration or Java configuration as per requirements.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <property name="hibernate.connection.driver_class">org.h2.Driver</property>
      <property name="hibernate.connection.url">jdbc:h2:mem:test</property>
      <property name="hibernate.connection.username">sa</property>
      <property name="hibernate.connection.password"></property>
      <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
      <property name="hibernate.show_sql">true</property>
      <property name="hibernate.format_sql">true</property>
      <property name="hibernate.hbm2ddl.auto">create-drop</property>
      <property name="hibernate.current_session_context_class">thread</property>
      <mapping class="com.howtodoinjava.basics.entity.EmployeeEntity" />
   </session-factory>
</hibernate-configuration>

3. Using EntityManager#persist()

The Jakarta persistence API provides method to fetch or persist an entity using its EntityManager interface. Hibernate (version 6 onwards) internally implements Jakarta persistence so we can use this method directly.

EntityManagerFactory emf = Persistence.createEntityManagerFactory("H2DB");
EntityManager em = emf.createEntityManager();

EmployeeEntity emp = new EmployeeEntity();
emp.setEmail("demo-user@mail.com");
emp.setFirstName("demo");
emp.setLastName("user");

Assertions.assertNull(emp.getEmployeeId());

em.getTransaction().begin();
em.persist(emp);
em.getTransaction().commit();

Assertions.assertNotNull(emp.getEmployeeId());

To configure the datasource, we need to supply the META-INF/persistence.xml in the application classpath that will have all the configuration details.

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
    <persistence-unit name="H2DB">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>com.howtodoinjava.demo.entity.EmployeeEntity</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="jakarta.persistence.jdbc.driver"
                      value="org.h2.Driver"/>
            <property name="jakarta.persistence.jdbc.url"
                      value="jdbc:h2:mem:test"/>
            <property name="jakarta.persistence.jdbc.user" value="sa"/>
            <property name="jakarta.persistence.jdbc.password" value=""/>
            <property name="hibernate.show_sql" value="true"/>
            <!--<property name="hibernate.format_sql" value="true"/>-->
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        </properties>
    </persistence-unit>
</persistence>

3. Using HQL

Hibernate Query Language (HQL) supports two kinds of insert statement:

  • insert …​ values, where the attribute values to insert are given directly as tuples. This inserts a single row in the database, or multiple rows if we provide multiple tuples in the values clause.
  • insert …​ select, where the inserted attribute values are sourced from a subquery. This inserts many new rows or none at all.

For example, we can use the given statement to insert a EmployeeEntity record. Note that the INSERT statement must be executed by calling Query#executeUpdate().

em.createQuery(
            "insert EmployeeEntity (employeeId, firstName, lastName, email) " +
                "values (1, 'Lokesh', 'Gupta', 'howtodoinjava@gmail.com')")
        .executeUpdate();

4. Conclusion

In this hibernate tutorial, we learned to insert an object into the database using Session, EntityManager and HQL queries.

Happy Learning !!

Leave a Reply

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.