Careeroza
Hibernate Session API
Session = Hibernate EntityManager
Hibernate's own API predates JPA. Session extends EntityManager, so every JPA method works on it, plus some extras. In Spring you can get it from the EntityManager:
Session session = entityManager.unwrap(Session.class);
session.persist(product); // same as JPA
Product p = session.get(Product.class, 42L); // like find()
session.merge(product);
session.remove(product);
// Hibernate-only extras
session.setJdbcBatchSize(50);
List<Product> many = session.byMultipleIds(Product.class).multiLoad(1L, 2L, 3L);
Product bySku = session.bySimpleNaturalId(Product.class).load("SKU-BOAT-450"); // needs @NaturalIdDeprecated Methods You Will See in Old Code
| Old Hibernate 5 method | Hibernate 6 replacement |
|---|---|
session.save(p) | session.persist(p) |
session.update(p) | session.merge(p) |
session.saveOrUpdate(p) | persist for new, merge for existing |
session.delete(p) | session.remove(p) |
session.load(Product.class, id) | session.getReference(Product.class, id) |
session.createCriteria(...) | JPA Criteria API (CriteriaBuilder) |
Tip: In interviews, mention that save/update/saveOrUpdate were deprecated in Hibernate 6.0 in favour of the JPA methods.
Plain Hibernate Bootstrapping
SessionFactory sessionFactory = new Configuration()
.configure() // reads hibernate.cfg.xml
.addAnnotatedClass(Product.class)
.buildSessionFactory();
sessionFactory.inTransaction(session -> { // Hibernate 6: begins, commits or rolls back for you
session.persist(new Product("SKU-USB-C", "USB-C Cable", new BigDecimal("199.00"), 500, "Accessories"));
});
Product p = sessionFactory.fromTransaction(session -> session.get(Product.class, 1L));<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:h2:mem:shopease</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>