CRUD Operations - bobocode-breskul/bibernate GitHub Wiki
Create (session.persist)
To store an entity in the database, use the persist
method of objects of the Session
class. The method takes an entity as input. The entity must be marked with all the necessary annotations (see the documentation). After saving the entity in the database, the method also "fills" the identifier field (id) and adds this entity to the context. If such an entity already exists in the context, it is not saved.
Example:
Person person = new Person();
person.setName("Biber");
person.setAge(20);
session.persist(person);
Read (session.findById)
To get an entity from the database by its identifier, use the findById
method of objects of the Session
class. The method takes as input the entity class and the id value and returns the found entity. If the desired entity is in the context, then the entity from the context is returned, otherwise a query to the database is made. You can also use an overloaded version of the method that accepts an additional LockType
parameter (possible values are PESSIMISTIC_READ
, PESSIMISTIC_WRITE
), which allows you to use an appropriate locking strategy at the database level.
Examples:
Person person = session.findById(Person.class, 1L);
Person person = session.findById(Person.class, 1L, LockType.PESSIMISTIC_READ);
Update (session.mergeEntity)
For merging the provided entity with the existing entity in the persistence context or database use the mergeEntity
of objects of the Session
class. The method takes as input the entity to be merged and returns the updated managed entity. If the entity is already present in the persistence context, it copies the changed values from the provided entity to the existing entity. If the entity is not present in the persistence context, it attempts to find the entity in the database and copies the changed values from the provided entity to the found entity. If the entity is not found in the database, it persists a copy of the provided entity. Provided entity object never becomes managed.
Example:
Person person = new Person();
person.setId(1L);
person.setName("Biber");
person.setAge(20);
Person updatedPerson = session.mergeEntity(person);
Delete (session.delete)
To delete an entity from the database, use the delete
method of objects of the Session
class. The method takes the entity to be deleted as a parameter. In addition to being deleted from the database, the entity is also deleted from the context.
Example:
Person person = a new Person();
person.setId(1L);
person.setName("Biber");
person.setAge(20);
session.delete(person);
All of the listed CRUD operations are used through the #Action Queue.