Everything the ORM does isn’t done on the DB directly, but rather happens in the context — a container that manages instances of your entity classes. When you use Hibernate (or any ORM), you define entities (Java classes) that mirror the structure of corresponding database tables. Each entity field represents a column, and each object instance represents a row.
We annotate entity classes with @Entity, denoting that the class models some structure in the
DB. We also have @Table, used to customize how the class is named in the DB. Both @Entity and
@Table can take a name parameter — for @Entity that name is used inside the persistence
context, while for @Table it names the database table directly.
To grab something from the DB by its primary key, call find() on the EntityManager (the
context) — it fetches the entity from the DB and places it in the context.
Calling save() outside of creating a new object is redundant, because Hibernate auto-detects all
changes in the context and syncs them with the DB when the transaction commits. save() is
necessary when persisting something new, and is a combination of merge and persist. But when
you just change values, there’s no update() method on EntityManager.
Even calling remove() doesn’t remove the item from the DB — it removes it from the context, so
no query is sent to the database until the transaction is committed.
Other methods:
merge()— merges an entity from outside the context into the context (an update operation)persist()— adds a new entity to the context (a create/insert operation)find()— find by primary key; gets from the DB and adds to the context if not already presentremove()— marks an entity for removalrefresh()— mirrors the context from the databasedetach()— takes the entity out of the context
EntityManagerFactory emf = new HibernatePersistenceProvider() .createContainerEntityManagerFactory(new CustomPersistenceUnitInfo("persistence-unit", new HashMap<>()));
EntityManager em = emf.createEntityManager(); // this is our context
try { em.getTransaction().begin();
Employee e1 = em.find(Employee.class, 1); // find employee with id of 1 e1.setName("sarfo"); // updates the name in the context
em.remove(e1); // removes e1 from the context, not the db
em.getTransaction().commit(); // detects the change in the context and updates it in the db} finally { em.close();}