780 likes | 817 Views
Explore best practices for using EJB 3.2 and JPA 2.1 with real-life examples presented by Ahmad Gohar, an IBM Architect. Learn about entity encryption, using facades, JPA EntityListeners, Attribute Converter, and more. Discover how to handle encryption without affecting your application and maintain a clean separation between persistence and security layers. Dive into converting data types like BigDecimal and Java 8 Date Time API. Unravel the limitations of JPA 2.1 with LocalDate and LocalDateTime storage and how to persist them efficiently.
E N D
EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples [CON7535] EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples [CON7535]Ahmad Gohar, ArchitectIBM Experienced IT-SpecialistClient Innovation Center (CIC)
Ahmad (Nabil) Gohar • Architect & Technical Team Lead (9Y.) • Client Innovation Center CIC | IBM Egypt • IBM Certified Experienced IT Specialist • M.Sc. in Information System, FCI, Egypt • MIBA in Global Management, ESLSCA, France • OCEJPA, OCPWCD,OCPJP, OCP PL/SQL, MCP(s) • JAVA Community Process (JCP) Member • Blogger Author and Academic Researcher
Entity Encrypt String Data
Data Model Oracle HR Employees Table
The EncryptorBean • The EncryptorBean handles encryption but does not know what’s being encrypted.
Encryption Main requirements • Provide a transparent encryption that does not affect the application, • Develop application and security/encryption by two different teams/persons.
1- Encryption Using Facade Facade
1- Encryption Using Facade • Persistence manager quietly handles your encryption • Architecture demands a tight and unnecessary binding between your persistence and security designs. • You can’t touch one without also touching the other.
2- JPA EntityListeners • A solution is JPA EntityListeners • These are Listener classes that can provide methods called before or after database object creation, deletion or modification. • @PrePersist • @PreUpdate • @PreRemove • @PostLoad • @PostUpdate • @PostRemove • To keep a clean separation between the persistence and security layers the listener does nothing but call a service that handles the encryption.
3- Converter (AttributeConverter) @JPA 2.1 • Attribute Converter provide a nice and easy way to define a custom mapping between your property on the entity and the database column. • The only thing that is needed is a class that • implements the AttributeConverter interface • annotated with @Converter.
Converter (AttributeConverter) Converter Class
Converter (AttributeConverter) JPA Facade
Entity Listeners or Attribute Converter? Entity Listener Adv. Entity Listener Drawbacks Its implementation is specific for an entity More complex than the implementation of a Attribute Converter. If we need to encrypt an additional attribute, you need to change the implementation. • The entity listener can use multiple attributes of the entity during encryption. • So we can join multiple attributes, encrypt them and store the encrypted data in one database field.
Entity Listeners or Attribute Converter? The Converter Adv. The Converter Drawbacks The encrypted entity attribute cannot be marked as transient. This might result in vulnerabilities if the entity gets written to the disk. • Can be used to encrypt any String attribute of any entity. • By using the XML based configuration to register the converter to the entity attribute, it requires no change in the source code of the application.
Entity Listeners or Attribute Converter? • Both approaches have their pros and cons. • You have to decide which advantages and disadvantages are more important to you.
Entity Encrypt Object Data
BigDecimal Converter Converter Class
JSR 310 Java 8 Date Time API
Java 8 Date Time API • A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03. • LocalDate is an immutable date-time object that represents a date. • Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. • The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. • However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.
Does JPA 2.1 support LocalDate and LocalDateTime? The answer is simple, NO • JPA 2.1 was released before Java 8 and the Date and Time API simply didn’t exist at that point in time. • Therefore the @Temporal annotation can only be applied to attributes of type java.util.Date and java.util.Calendar. Why JPA not support LocalDate and LocalDateTime?
Entity How to persist LocalDate and LocalDateTime with JPA
How to persist LocalDate and LocalDateTime with JPA Converter Class
Converting LocalDateTime • The attribute converter for LocalDateTime is basically the same. • You need to implement the AttributeConverter<LocalDateTime, Timestamp> interface and the converter needs to be annotated with the @Converter annotation. • Similar to the LocalDateConverter, the conversion between a LocalDateTime and an java.sql.Timestamp is done with the conversion methods of Timestamp.
LocalDate/LocalDateTime Conclusion • JPA 2.1 was released before Java 8 and therefore doesn’t support the new Date and Time API. • If you want to use the new classes (in the right way), you need to define the conversion to java.sql.Date and java.sql.Timestamp yourself. • This can be easily done by implementing the AttributeConverter<EntityType, DatabaseType> interface and annotating the class with @Converter(autoApply=true). • By setting autoApply=true, the converter will be applied to all attributes of the EntityType and no changes on the entity are required.
Entity Data fetching strategy
Data fetching strategy • EAGER – immediate • LAZY – load only when needed • Lazy is good for large objects with deep relationship hierarchies
Lazy Loading Best Practices • Lazy load fields and relationships that are not used frequently • One-many/many-may relationships are lazy loaded by default • Lazy load CLOB/BLOB if possible • Accessing a LAZY relationship from a detached entity • May get a null • May get a previously cached value • May get an exception
Entity | Data Fetching Strategy ways to initialize lazy relations
Example JPA
2. Fetch Join in JPQL JPA Facade
4. Named Entity Graph JPA Facade
5. Dynamic Entity Graph Facade
5. Dynamic Entity Graph Advantage Disadvantage • If we need lots of use case specific entity graphs, it might be better to define the entity graph within the specific Java code and to not add an additional annotation to the entity. • Avoids entities with dozens of annotations. • The dynamic entity graph requires more code and an additional method to be reusable.
5 ways to initialize lazy relations and when to use them • Initializing a lazy relation via calling a method on a mapped relation causes an additional query. This should be avoided for performance reasons. • Fetch joins in JPQL statements reduce the number of queries to one but we might need a lot of different queries. • The Criteria API also supports fetch joins and we need specific code for each combination of relations that shall be initialized. • Named entity graphs are a good solution, if we will reuse the defined graph in our code. • Dynamic entity graphs can be the better solution, if we need to define a use case specific graph.
Schemas and Queries Queries
Query JPQL JPA Criteria
Query JPA Criteria with Metamodel
Schemas and Queries define named queries at runtime
3 steps to define a named query at runtime • Create a Query. • This can be done as a JPQL, native or criteria query. • You can also define additional hints and settings for the query. • Find a name for your query that is unique within your persistence unit. • If there is already a named query defined for the name, the query will be updated. • Use the Query and name to call the addNamedQuery(String name, Query query) method on the EntityManagerFactory.