Upgrade to Pro — share decks privately, control downloads, hide ads and more …

EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535

Ahmad Gohar
October 28, 2015

EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535

Session ID: CON7535
Session Title: EJB 3.2/JPA 2.1 Best Practice with life examples
Session Type: Conference Session
Session Abstract:
This session’s speaker, an architect, discusses lessons learned from using JPA and EJB to support a high-volume, high-performance applications. These best practices don't only involve JPA/EJB but also its integration with other Java EE 7 technologies. They also include coding best practices, testing and production practices. The presentation focuses primarily on some Key concepts such as persistence context, lazy loading, caching, flushing, dirty checking, transaction and connection demarcation. This is a fast-paced presentation with many code samples. Categories covered include configuration, JPA, concurrency, performance tuning, exception handling and many more.

Ahmad Gohar

October 28, 2015
Tweet

More Decks by Ahmad Gohar

Other Decks in Programming

Transcript

  1. © 2015 IBM Corporation
    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, Architect
    IBM Experienced IT-Specialist
    Client Innovation Center (CIC)
    1

    View Slide

  2. © 2015 IBM Corporation
    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
    2

    View Slide

  3. © 2015 IBM Corporation
    3

    View Slide

  4. © 2015 IBM Corporation
    4

    View Slide

  5. © 2015 IBM Corporation
    5

    View Slide

  6. © 2015 IBM Corporation
    6

    View Slide

  7. © 2015 IBM Corporation
    ENCRYPT STRING DATA
    Entity
    7

    View Slide

  8. © 2015 IBM Corporation
    Data Model
    Oracle HR Employees Table
    8

    View Slide

  9. © 2015 IBM Corporation
    The EncryptorBean
    The EncryptorBean handles encryption but does not
    know what’s being encrypted.
    9

    View Slide

  10. © 2015 IBM Corporation
    Encryption Main requirements
    Provide a transparent encryption that does not
    affect the application,
    Develop application and security/encryption by two
    different teams/persons.
    10

    View Slide

  11. © 2015 IBM Corporation
    1- Encryption Using Facade
    Facade
    11

    View Slide

  12. © 2015 IBM Corporation
    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.
    12

    View Slide

  13. © 2015 IBM Corporation
    2- JPA EntityListeners
    13

    View Slide

  14. © 2015 IBM Corporation
    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.
    14

    View Slide

  15. © 2015 IBM Corporation
    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.
    15

    View Slide

  16. © 2015 IBM Corporation
    Converter (AttributeConverter)
    16
    Converter Class

    View Slide

  17. © 2015 IBM Corporation
    Converter (AttributeConverter)
    17
    JPA
    Facade

    View Slide

  18. © 2015 IBM Corporation
    Entity Listeners or Attribute Converter?
    Entity Listener Adv.
    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 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.
    18

    View Slide

  19. © 2015 IBM Corporation
    Entity Listeners or Attribute Converter?
    The Converter Adv.
    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.
    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.
    19

    View Slide

  20. © 2015 IBM Corporation
    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.
    20

    View Slide

  21. © 2015 IBM Corporation
    ENCRYPT OBJECT DATA
    Entity
    21

    View Slide

  22. © 2015 IBM Corporation
    BigDecimal Converter
    22

    View Slide

  23. © 2015 IBM Corporation
    BigDecimal Converter
    23
    Converter Class

    View Slide

  24. © 2015 IBM Corporation
    BigDecimal Converter
    24
    JPA

    View Slide

  25. © 2015 IBM Corporation
    JAVA 8 DATE TIME API
    JSR 310
    25

    View Slide

  26. © 2015 IBM Corporation
    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.
    26

    View Slide

  27. © 2015 IBM Corporation
    Java 8 Date Time API
    27

    View Slide

  28. © 2015 IBM Corporation
    Does JPA 2.1 support LocalDate and LocalDateTime?
    The answer is simple,
    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.
    28
    Why JPA not support LocalDate and LocalDateTime?
    NO

    View Slide

  29. © 2015 IBM Corporation
    HOW TO PERSIST
    LOCALDATE AND
    LOCALDATETIME WITH JPA
    Entity
    29

    View Slide

  30. © 2015 IBM Corporation
    How to persist LocalDate and LocalDateTime with JPA
    30
    Converter Class

    View Slide

  31. © 2015 IBM Corporation
    How to persist LocalDate and LocalDateTime with JPA
    31
    JPA

    View Slide

  32. © 2015 IBM Corporation
    Converting LocalDateTime
     The attribute converter for LocalDateTime is basically the same.
     You need to implement the AttributeConverter 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.
    32

    View Slide

  33. © 2015 IBM Corporation
    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 AttributeConverterDatabaseType> 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.
    33

    View Slide

  34. © 2015 IBM Corporation
    DATA FETCHING STRATEGY
    Entity
    34

    View Slide

  35. © 2015 IBM Corporation
    Data fetching strategy
     EAGER – immediate
     LAZY – load only when needed
     Lazy is good for large objects with deep relationship hierarchies
    35

    View Slide

  36. © 2015 IBM Corporation
    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
    36

    View Slide

  37. © 2015 IBM Corporation
    WAYS TO INITIALIZE LAZY
    RELATIONS
    Entity | Data Fetching Strategy
    37

    View Slide

  38. © 2015 IBM Corporation
    JPA
    38
    Example

    View Slide

  39. © 2015 IBM Corporation
    1. Call a method on the mapped relation
    Facade
    39

    View Slide

  40. © 2015 IBM Corporation
    2. Fetch Join in JPQL
    Facade
    40
    JPA

    View Slide

  41. © 2015 IBM Corporation
    3. Fetch Join in Criteria API
    Facade
    41

    View Slide

  42. © 2015 IBM Corporation
    4. Named Entity Graph
    JPA
    Facade
    42

    View Slide

  43. © 2015 IBM Corporation
    5. Dynamic Entity Graph
    Facade
    43

    View Slide

  44. © 2015 IBM Corporation
    5. Dynamic Entity Graph
    Advantage
    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.
    44
    Disadvantage
    The dynamic entity graph requires more code and an
    additional method to be reusable.

    View Slide

  45. © 2015 IBM Corporation
    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.
    45

    View Slide

  46. © 2015 IBM Corporation
    QUERIES
    Schemas and Queries
    46

    View Slide

  47. © 2015 IBM Corporation
    Query
    JPQL
    JPA Criteria
    47

    View Slide

  48. © 2015 IBM Corporation
    Query
    JPA Criteria with Metamodel
    48

    View Slide

  49. © 2015 IBM Corporation
    DEFINE NAMED QUERIES AT
    RUNTIME
    Schemas and Queries
    49

    View Slide

  50. © 2015 IBM Corporation
    3 steps to define a named query at runtime
    1. 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.
    2. 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.
    3. Use the Query and name to call the addNamedQuery(String name, Query query) method
    on the EntityManagerFactory.
    50

    View Slide

  51. © 2015 IBM Corporation
    Named Query at Runtime
    Define the Named Query
    Call the Named Query
    51

    View Slide

  52. © 2015 IBM Corporation
    JPQL ENHANCEMENTS
    Schemas and Queries
    52

    View Slide

  53. © 2015 IBM Corporation
    JPQL enhancements
    We can now use the keyword ON to define
    additional join parameters
    call database functions by using FUNCTION
    downcast entities with TREAT.
    53

    View Slide

  54. © 2015 IBM Corporation
    JPQL enhancement (FUNC)
    54

    View Slide

  55. © 2015 IBM Corporation
    BULK UPDATES
    Schemas and Queries
    55

    View Slide

  56. © 2015 IBM Corporation
    Bulk Updates
    56

    View Slide

  57. © 2015 IBM Corporation
    Bulk Updates
    57

    View Slide

  58. © 2015 IBM Corporation
    STORED PROCEDURES IN JPA
    Schemas and Queries
    58

    View Slide

  59. © 2015 IBM Corporation
    4 different modes of parameters
     IN:
    – for input parameters,
     OUT:
    – for output parameters,
     INOUT:
    – for parameters which are used for input and output and
     REF_CURSOR:
    – for cursors on a result set .
    59

    View Slide

  60. © 2015 IBM Corporation
    Oracle Stored Procedure
    60

    View Slide

  61. © 2015 IBM Corporation
    Named Stored Procedure
    61

    View Slide

  62. © 2015 IBM Corporation
    Named Stored Procedure
    62

    View Slide

  63. © 2015 IBM Corporation
    Stored Procedure Query
    63

    View Slide

  64. © 2015 IBM Corporation
    GENERATING DB SCHEMA
    Schemas and Queries
    64

    View Slide

  65. © 2015 IBM Corporation
    Generating DB Schema
     javax.persistence.schema-generation.database.action
     javax.persistence.schema-generation.scripts.action
     javax.persistence.schema-generation.create-source
     javax.persistence.schema-generation.drop-source
     javax.persistence.schema-generation.create-database-schemas
     javax.persistence.schema-generation.scripts.create-target
     javax.persistence.schema-generation.scripts.drop-target
     javax.persistence.database-product-name
     javax.persistence.database-major-version
     javax.persistence.database-minor-version
     javax.persistence.schema-generation.create-script-source
     javax.persistence.schema-generation.drop-script-source
     javax.persistence.schema-generation.connection
     javax.persistence.sql-load-script-source
    65

    View Slide

  66. © 2015 IBM Corporation
    EJB LITE
    EJB
    66

    View Slide

  67. © 2015 IBM Corporation
    More features in EJB.Lite
    Asynchronous session bean
    Non-persistent EJB Timer service
    67

    View Slide

  68. © 2015 IBM Corporation
    STATEFUL SESSION BEAN
    EJB
    68

    View Slide

  69. © 2015 IBM Corporation
    Stateful Session Bean Life Cycle
    69

    View Slide

  70. © 2015 IBM Corporation
    Opt-out of passivation for stateful session bean
    70

    View Slide

  71. © 2015 IBM Corporation
    TIMERSERVICE
    EJB
    71

    View Slide

  72. © 2015 IBM Corporation
    TimerService
     TimerService.getAllTimers
    – a newly added convenience API that returns all timers in the same bean.
    – This is only for displaying the list of timers as the timer can only be cancelled by its
    owner.
    72

    View Slide

  73. © 2015 IBM Corporation
    Painless Persistence
    Invest in some JPA skills
    Design your persistent objects
    Create a services layer (DAOs are not sufficient)
    Avoid cool but expensive features (e.g. Cascade)
    and always work with the DBAs
    Don't blindly do anything – always think before you
    code!
    73

    View Slide

  74. © 2015 IBM Corporation
    Wrap up
    74

    View Slide

  75. © 2015 IBM Corporation
    Wrap up
    75
    Encrypt String Data (AttributeConverter)
    Encrypt Object Data (AttributeConverter)
    Java 8 Date Time API (AttributeConverter)
    Data fetching strategy
    ways to initialize lazy relations(Named Entity Graph, Dynamic Entity
    Graph)
    Bulk Updates (Criteria Update)
    stored procedures in JPA (Named Stored Procedure, Stored Procedure
    Query)
    define named queries at runtime
    JPQL Enhancements

    View Slide

  76. © 2015 IBM Corporation
    Q. & A.
    76
    https://about.me/ansgohar
    http://ansgohar.blogspot.co.uk
    https://eg.linkedin.com/in/ansgohar
    https://www.facebook.com/ansgohar
    https://twitter.com/ansgohar
    ansgohar

    View Slide

  77. © 2015 IBM Corporation
    77

    View Slide

  78. © 2015 IBM Corporation
    78

    View Slide