Skip to content

Basic entity management

Having defined and modeled entities and their relations , we can start managing them from the code level.

Hibernate abstracts the execution of simple CRUD operations on the basis of ready-made methods in the EntityManager interface, which is one of the interfaces that session extends.

CRUD operations

The examples will be based on the following entity:

import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Data
@NoArgsConstructor
public class Car {

  @Id
  @GeneratedValue
  private Long id;

  private String modelName;

  private String producer;

  private Double engineVolume;

  public Car(String modelName, String producer, Double engineVolume) {
    this.modelName = modelName;
    this.producer = producer;
    this.engineVolume = engineVolume;
  }
}

Note that the constructor we defined does not have the option to set the value of the identifier field because it is automatically generated by Hibernate (thanks to the @GeneratedValue annotation).

In order to save a non-existent row in the database, we need to use the persist method:

final Car car = new Car("Corolla", "Toyota", 2.0);
entityManager.persist(car);
System.out.println(car.getId()); // given ID, e.g. 1


In order to get the value of an entity from the database, we need to use the find method. The first argument is the type of entity we want to get, the second is the primary key value, e.g .:

Car car = entityManager.find(Car.class, 1L);
System.out.println(car); // Car(id=1, modelName=Corolla, producer=Toyota, engineVolume=2.0)

NOTE: The find method may returnnull if a record with the given primary key does not exist.


We can also remove the created entity from the database by using the remove method, e.g:

Car car = entityManager.find(Car.class, 1L);
System.out.println(car); // Car(id=1, modelName=Corolla, producer=Toyota, engineVolume=2.0)
entityManager.remove(car);


The last operation we can use is updating an existing record in the table. This is done with the merge method, which, unlike thepersist method, returns the updated object:

Car car = entityManager.find(Car.class, 1L);
car.setEngineVolume(1.8);
Car updatedCar = entityManager.merge(car);

NOTE:: The methods persist, merge, and remove require transactions to perform the operation, and may throw exceptions when incorrect arguments are passed (e.g. trying to update or delete a non-existent entity will throw an exception of type IllegalArgumentException).