EntityManagerem=emf.createEntityManager();em.getTransaction().begin();ClusterNoderef1=em.find(ClusterNode.class,1L);// hits DB: SELECTClusterNoderef2=em.find(ClusterNode.class,1L);// cache hit: NO SQL// Java object identity guaranteed within same persistence context:assertref1==ref2;// TRUE — same instance, not just equalSystem.out.println("Identity map verified: "+(ref1==ref2));em.getTransaction().commit();em.close();
em.getTransaction().begin();ClusterNodenode=em.find(ClusterNode.class,1L);// Managed state// Just modify the field — no em.merge() or em.save() needed:node.setStatus(NodeStatus.MAINTENANCE);node.getHardware().setRamGb(128);em.getTransaction().commit();// Hibernate issues: UPDATE cluster_node SET status=? WHERE id=?
em.getTransaction().begin();ClusterNodenode=em.find(ClusterNode.class,1L);node.setStatus(NodeStatus.OFFLINE);// flush() — pushes pending SQL to DB but does NOT commit:em.flush();// Database now has OFFLINE but transaction is still open// Simulate another thread updating the DB directly...// refresh() — overwrites in-memory state with CURRENT DB row:em.refresh(node);// node.getStatus() now reflects whatever is in the DB (may have been changed externally)em.getTransaction().commit();
// entity is DETACHED after em.close():em.close();// Later, modify the detached entity:node.setCpuUsagePercent(95.5);// Open new EntityManager and merge:EntityManagerem2=emf.createEntityManager();em2.getTransaction().begin();// WRONG — do not use the argument:// em2.merge(node); ← node is still detached after this!// CORRECT — use the returned managed instance:ClusterNodemanagedNode=em2.merge(node);// copies state, returns managed copymanagedNode.setLastCheckedAt(Instant.now());// now modifying the managed instanceem2.getTransaction().commit();em2.close();
// In-entity callbacks (no parameter):@Entity@EntityListeners(AuditListener.class)// attach external listenerpublicclassClusterNode{@PrePersistprivatevoidonPrePersist(){this.createdAt=Instant.now();this.version=0;}@PostLoadprivatevoidonPostLoad(){// Compute transient field from loaded state — NOT persisted:this.durationOpenSeconds=Duration.between(createdAt,Instant.now()).getSeconds();}}
// External listener class (entity passed as parameter):publicclassAuditListener{@PrePersistpublicvoidonPrePersist(Objectentity){System.out.printf("[AUDIT] PRE_PERSIST: %s%n",entity.getClass().getSimpleName());}@PostPersistpublicvoidonPostPersist(Objectentity){System.out.printf("[AUDIT] POST_PERSIST: %s (committed)%n",entity.getClass().getSimpleName());}@PreUpdatepublicvoidonPreUpdate(Objectentity){System.out.printf("[AUDIT] PRE_UPDATE: %s%n",entity.getClass().getSimpleName());}@PostUpdatepublicvoidonPostUpdate(Objectentity){System.out.printf("[AUDIT] POST_UPDATE: %s%n",entity.getClass().getSimpleName());}@PreRemovepublicvoidonPreRemove(Objectentity){System.out.printf("[AUDIT] PRE_REMOVE: %s%n",entity.getClass().getSimpleName());}@PostRemovepublicvoidonPostRemove(Objectentity){System.out.printf("[AUDIT] POST_REMOVE: %s (deleted from DB)%n",entity.getClass().getSimpleName());}}