Spring Hibernate JPA by zed18012

VIEWS: 80 PAGES: 9

									Spring Hibernate & JPA

        Mike Calvo
mike@citronellasoftware.com
    Spring with Hibernate & JPA
• Spring provides simplifications to the
  Hibernate and JPA APIs
• Follows common template and DAOSupport
  patterns
• Provides transactional integration
• Open Session in View web pattern
             Hibernate Support
• AnnotationSessionFactoryBean
  – Provides Hibernate SessionFactory
  – Configure in application context
  – Set data source, annotated classes, and hibernate
    properties
• HibernateTemplate
  – Template pattern for Hibernate Session
• HibernateDaoSupport
  – Simple base class that provides access to a
    HibernateTemplate
                JPA Support
• Entity Manager Factories
  – Application-managed (we will use this)
  – Container-managed (for JEE containers)
• JpaTemplate
• JpaDaoSupport
        Entity Manager Factory
• Application Managed (Use this)
  – LocalEntityManagerFactoryBean
  – Configure persistenceUnit property with the
    persistence unit name from your persistence.xml file
  – Can be injected into your services as an
    EntityManager
• Container Managed
  – LocalContainerEntityManagerFactoryBean
  – Used for JEE environments
  – More configurable than
 Benefits of Hibernate/JPA Templates
• Simplified querying
  – Typically single method call
• Reduced exception handling code
            Template Warning
• Code improvement using Hibernate or JPA
  Templates not as dramatic as when using JDBC
• Session/EntityManager management can be a
  problem using these approaches
  – By default each call to the template opens a new
    Session on EntityManager
  – Lazy loading & updating existing items may not work
• Can be tricky when used without Spring
  transaction management
• Recommendation: only use in conjunction with
  Spring transaction management
      Transaction Management
• Spring provides implementations of
  Transaction managers for both Hibernate and
  JPA:
  – HibernateTransactionManager
  – JpaTransactionManager
• These can be used to back Spring annotation-
  based transaction management
  – Will automatically commit or rollback
    appropriately on annotated methods
         Open Session in View
• Lazy loading can be a problem in web
  applications where the Session/EntityManager
  is closed on each request
• Spring implements a pattern to help minimize
  this problem
• More on this later

								
To top