-
-
Save XMENCODE/ab0dc29c481d8e1d04b2fc23c44c58c6 to your computer and use it in GitHub Desktop.
JPA Cheatsheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| JPA (Java Persistence API) | |
| Transaction Management with an Entity-Mananger: | |
| --- | |
| entityManager.getTransaction().begin(); | |
| entityManager.persist(<some-entity>); | |
| entityManager.getTransaction().commit(); | |
| entityManager.clear(); | |
| SomeEntity entity = entityManager.find(SomeEntity.class, 1); | |
| --- | |
| @OneToOne's fetch type is EAGER by default | |
| Lists + Sets fetch type is LAZY by default | |
| Two types of Lazy Loading implementations | |
| 1. Proxying the object (default in Hibernate) by creating a Subclass of that object at runtime and overwrite the get methods. | |
| This is done by the JavaAssist lib. | |
| 2. ByteCode Enhancement (default in EclipseLink): Add special logic to the get methods inside the Java Bytecode | |
| LazyInitializationExcepiton: | |
| Entity Lifecycle | |
| New ---> em.persist ---> Managed | |
| New ---> em.merge ---> Managed | |
| Managed ---> em.remove ---> Removed | |
| Managed ---> em.find ---> Managed | |
| Managed ---> query.getResultList ---> Managed | |
| Managed ---> query.getSingleResult ---> Managed | |
| Managed ---> em.detach ---> Detached | |
| Managed ---> em.close ---> Detached | |
| Managed ---> em.clear ---> Detached | |
| Detached ---> em.merge ---> Managed | |
| Ein neu angelegtes Entity Object ist im Zustand "New". | |
| Managed - Es gibt einen Entity-Manager, der für dieses Objekt verantwortlich ist: | |
| Vorteile: - Es werden automatisch Änderungen getrackt. | |
| Beim nächsten Transaktions-Commit werden nur die Änderungen in die DB geschrieben. | |
| Lazy Loading funktioniert | |
| Detached - Lazy Loading muss nicht zwangsweise funktionieren | |
| // Use a database sequence on id field | |
| @Entity | |
| @Table(name = "ADDRESS") | |
| public class Address { | |
| @Id | |
| @SequenceGenerator( | |
| name = "address_seq", | |
| sequenceName = "address_seq", | |
| allocationSize = 1 | |
| ) | |
| @GeneratedValue( | |
| strategy = GenerationType.SEQUENCE, | |
| generator = "address_seq" | |
| ) | |
| private long id; | |
| } | |
| // Delete dependent children, when the parent is going to be deleted (child-entites are orphans (=Waisen) then) | |
| @OneToMany(mappedBy="foo", orphanRemoval=true) | |
| private List<Bikes> bikes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment