Tuesday, December 31, 2013

JBoss 4.2.x Spring 3 JPA Hibernate Tutorial

by Byron Kiourtzoglou on May 18th, 2010 | Filed in: Enterprise Java Tags: EclipseHSQLDBJBossJBoss HibernateJBoss TreeCacheJGroupsJNDIJPAJTAMySQL,Spring
After spending many hours searching the web, trying to find the most efficient way to use Spring, JPA and Hibenate for several projects we concluded to the configuration that will be presented below. Integrating Spring with JPA and Hibernate consists of several steps :
  • Configuration of the Spring container
  • Configuration of the JPA ORM layer
  • Configuration of Hibernate Second lvl cache (if needed)
Keep in mind that we assume we are operating inside a J2EE container as far as data-sources are concerned, so we are going to lookup an existing data-source from JNDI and use it. The files that we are going to configure are those described below :
  1. The spring.xml file, that drives the spring container.
  2. The persistence.xml file, that drives the JPA ORM layer
  3. The second lvl cache file e.g. treecache.xml for the JBoss TreeCache provider (if needed)
An example spring.xml file is presented below :
01
02
03
04
05
06
 xsi:schemaLocation="
07
08
09
10
11
12
13
>
14

15
 <context:component-scan base-package="com.mycomp.mypackage" />
16

17
 <task:annotation-driven executor="myExecutor" scheduler="myScheduler" />
18

19
 <task:executor id="myExecutor" pool-size="5" />
20

21
 <task:scheduler id="myScheduler" pool-size="10" />
22

23
 <tx:annotation-driven />
24

25
 <bean id="entityManagerFactory"
26
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
27
  <property name="persistenceUnitName" value="MyPersistenceUnit" />
28
 </bean>
29

30
 <bean id="transactionManager"
31
  class="org.springframework.transaction.jta.JtaTransactionManager">
32
  <property name="transactionManagerName" value="java:/TransactionManager" />
33
  <property name="userTransactionName" value="UserTransaction" />
34
 </bean>
35

36
</beans>
A few things to notice here
  • Change the base-package attribute of the context:component-scan tag to whatever is the base package of your project so as to be scanned for Spring components (services, DAOs etc)
  • Change the value attribute of entityManagerFactory bean persistentUnitName property to the name of your persistent unit as dictated in the persistence.xml file
An example persistence.xml file is presented below :
01
02
03
 xsi:schemaLocation=
04
05
06
 version="1.0">
07

08
 <persistence-unit name="MyPersistenceUnit" transaction-type="JTA">
09

10
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
11
  <jta-data-source>java:/MyDataSource</jta-data-source>
12
  
13
  <properties>
14
   <property name="hibernate.dialect" 
15
     value="org.hibernate.dialect.HSQLDialect"/>
16
   <property name="hibernate.hbm2ddl.auto" value="update"/>
17
   <property name="hibernate.show_sql" value="false"/>
18
   <property name="hibernate.transaction.manager_lookup_class" 
19
     value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
20

21
   
22
   
34
  </properties>
35

36
 </persistence-unit>
37

38
</persistence>
A few things to notice here :
  • The persistence unit name, here MyPersistenceUnit, must match the value in the spring.xml file
  • The transaction type can have JTA or LOCAL values, our assumption is that we are deploying inside a JTA enabled container so we can make use of global transactions (JTA), in any other case you should use the LOCAL value
  • As mentioned above we assume that we are deploying in a J2EE container with data-sources declared in separate files and located in JNDI, so we dictate JPA to use the data-source found under the specific JNDI name, you should change this value according to your data-source JNDI name
  • We dictate hibernate to use the Hypersonic dialect, you should change this value according to your data-source, e.g. for MySQL this value should be org.hibernate.dialect.MySQLDialect (for myISAM engine) or org.hibernate.dialect.MySQLInnoDBDialect (for InnoDB engine)
  • We dictate hibernate to lookup our JTA transaction manager, e.g if we are deploying inside JBoss we use the specified value, you should change this value according to your environment
  • If you want to enable Hibernate second lvl cache just uncomment the specified configuration directives
An example second lvl cache (JBoss tree cache – treecache.xml) file is presented below :
01
<server>
02

03
 <classpath codebase="./lib" archives="jboss-cache.jar, jgroups.jar" />
04

05
 <mbean code="org.jboss.cache.TreeCache" name="jboss.cache:service=TreeCache">
06
  <depends>jboss:service=Naming</depends>
07
  <depends>jboss:service=TransactionManager</depends>
08
  <attribute name="TransactionManagerLookupClass">
09
   org.jboss.cache.JBossTransactionManagerLookup</attribute>
10
  <attribute name="IsolationLevel">REPEATABLE_READ</attribute>
11
  <attribute name="CacheMode">LOCAL</attribute>
12
  <attribute name="UseReplQueue">false</attribute>
13
  <attribute name="ReplQueueInterval">0</attribute>
14
  <attribute name="ReplQueueMaxElements">0</attribute>
15
  <attribute name="ClusterName">TreeCache-Cluster</attribute>
16
  <attribute name="ClusterConfig">
17
   <config>
18
    <UDP mcast_addr="228.1.2.3" mcast_port="48866" ip_ttl="64"
19
     ip_mcast="true" mcast_send_buf_size="150000" mcast_recv_buf_size="80000"
20
     ucast_send_buf_size="150000" ucast_recv_buf_size="80000" loopback="false" />
21
    <PING timeout="2000" num_initial_members="3" up_thread="false"
22
     down_thread="false" />
23
    <MERGE2 min_interval="10000" max_interval="20000" />
24
    <FD_SOCK />
25
    <VERIFY_SUSPECT timeout="1500" up_thread="false"
26
     down_thread="false" />
27
    <pbcast.NAKACK gc_lag="50" retransmit_timeout="600,1200,2400,4800"
28
     max_xmit_size="8192" up_thread="false" down_thread="false" />
29
    <UNICAST timeout="600,1200,2400" window_size="100"
30
     min_threshold="10" down_thread="false" />
31
    <pbcast.STABLE desired_avg_gossip="20000" up_thread="false"
32
     down_thread="false" />
33
    <FRAG frag_size="8192" down_thread="false" up_thread="false" />
34
    <pbcast.GMS join_timeout="5000" join_retry_timeout="2000"
35
     shun="true" print_local_addr="true" />
36
    <pbcast.STATE_TRANSFER up_thread="true"
37
     down_thread="true" />
38
   </config>
39
  </attribute>
40
  <attribute name="FetchInMemoryState">true</attribute>
41
  <attribute name="InitialStateRetrievalTimeout">20000</attribute>
42
  <attribute name="SyncReplTimeout">20000</attribute>
43
  <attribute name="LockAcquisitionTimeout">15000</attribute>
44
  <attribute name="EvictionPolicyClass"></attribute>
45
  <attribute name="UseMarshalling">false</attribute>
46
 </mbean>
47

48
</server>
A few things to notice here
  • Update the path for the classloader to locate the two required files (jboss-cache.jar, jgroups.jar) for JBoss tree cache to work
  • This file configures the tree cache as a JBoss MBean service so it must be deployed in a JBoss application server, other configuration types are out of the scope of this tutorial and will not be discussed further. For configuring JBoss tree cache in another environment please refer to the appropriate documentation
That’s it, now let me present a sample DTO and DAO based on the configuration described above :
First the DTO class (EmployeeDTO)
01
package com.mycomp.myproject.dto;
02

03
import javax.persistence.Column;
04
import javax.persistence.Entity;
05
import javax.persistence.Id;
06
import javax.persistence.Table;
07

08
@Entity
09
@Table(name = "EMPLOYEE")
10
public class EmployeeDTO implements java.io.Serializable {
11
     
12
    private static final long serialVersionUID = 7440297955003302414L;
13

14
    @Id
15
    @Column(name="employee_id")
16
    private long employeeId;
17
     
18
    @Column(name="employee_name", nullable = false, length=30)
19
    private String employeeName;
20
     
21
    @Column(name="employee_surname", nullable = false, length=30)
22
    private String employeeSurname;
23
     
24
    @Column(name="job", length=50)
25
    private String job;
26
         
27
    public EmployeeDTO() {
28
    }
29

30
    public EmployeeDTO(int employeeId) {
31
        this.employeeId = employeeId;       
32
    }
33

34
    public EmployeeDTO(long employeeId, String employeeName, String employeeSurname,
35
            String job) {
36
        this.employeeId = employeeId;
37
        this.employeeName = employeeName;
38
        this.employeeSurname = employeeSurname;
39
        this.job = job;
40
    }
41

42
    public long getEmployeeId() {
43
        return employeeId;
44
    }
45

46
    public void setEmployeeId(long employeeId) {
47
        this.employeeId = employeeId;
48
    }
49

50
    public String getEmployeeName() {
51
        return employeeName;
52
    }
53

54
    public void setEmployeeName(String employeeName) {
55
        this.employeeName = employeeName;
56
    }
57

58
    public String getEmployeeSurname() {
59
        return employeeSurname;
60
    }
61

62
    public void setEmployeeSurname(String employeeSurname) {
63
        this.employeeSurname = employeeSurname;
64
    }
65

66
    public String getJob() {
67
        return job;
68
    }
69

70
    public void setJob(String job) {
71
        this.job = job;
72
    }
73

74
}
Following is the DAO class for accessing Employee data (EmployeeDTO)
01
package com.mycomp.myproject.dao;
02

03
import javax.annotation.PostConstruct;
04
import javax.persistence.EntityManagerFactory;
05

06
import org.springframework.beans.factory.annotation.Autowired;
07
import org.springframework.stereotype.Repository;
08

09
import com.mycomp.myproject.dto.EmployeeDTO;
10

11
@Repository("employeeDAO")
12
public class EmployeeDAO extends JpaDAO {
13
     
14
    @Autowired
15
    EntityManagerFactory entityManagerFactory;
16
     
17
    @PostConstruct
18
    public void init() {
19
        super.setEntityManagerFactory(entityManagerFactory);
20
    }
21
     
22
}
As you can see the EmployeeDAO class extends a basic DAO class (JpaDao). The EmployeeDAO class can contain specific queries concerning the EmployeeDTO object, but all CRUD operations can be handled from the basic DAO class (JpaDao) presented below :
01
package com.mycomp.myproject.dao;
02

03
import java.lang.reflect.ParameterizedType;
04
import java.util.List;
05

06
import javax.persistence.EntityManager;
07
import javax.persistence.PersistenceException;
08
import javax.persistence.Query;
09

10
import org.springframework.orm.jpa.JpaCallback;
11
import org.springframework.orm.jpa.support.JpaDaoSupport;
12

13
public abstract class JpaDAO extends JpaDaoSupport {
14
    protected Class entityClass;
15

16
    @SuppressWarnings("unchecked")
17
    public JpaDAO() {
18
        ParameterizedType genericSuperclass = (ParameterizedType) getClass()
19
                .getGenericSuperclass();
20
        this.entityClass = (Class) genericSuperclass
21
                .getActualTypeArguments()[1];
22
    }
23

24
    public void persist(E entity) {
25
        getJpaTemplate().persist(entity);
26
    }
27

28
    public void remove(E entity) {
29
        getJpaTemplate().remove(entity);
30
    }
31
     
32
    public E merge(E entity) {
33
        return getJpaTemplate().merge(entity);
34
    }
35
     
36
    public void refresh(E entity) {
37
        getJpaTemplate().refresh(entity);
38
    }
39

40
    public E findById(K id) {
41
        return getJpaTemplate().find(entityClass, id);
42
    }
43
     
44
    public E flush(E entity) {
45
        getJpaTemplate().flush();
46
        return entity;
47
    }
48
     
49
    @SuppressWarnings("unchecked")
50
    public List findAll() {
51
        Object res = getJpaTemplate().execute(new JpaCallback() {
52

53
            public Object doInJpa(EntityManager em) throws PersistenceException {
54
                Query q = em.createQuery("SELECT h FROM " +
55
                        entityClass.getName() + " h");
56
                return q.getResultList();
57
            }
58
             
59
        });
60
         
61
        return (List) res;
62
    }
63

64
    @SuppressWarnings("unchecked")
65
    public Integer removeAll() {
66
        return (Integer) getJpaTemplate().execute(new JpaCallback() {
67

68
            public Object doInJpa(EntityManager em) throws PersistenceException {
69
                Query q = em.createQuery("DELETE FROM " +
70
                        entityClass.getName() + " h");
71
                return q.executeUpdate();
72
            }
73
             
74
        });
75
    }
76
     
77
}
This tutorial concludes, with the second part, where we are going to discuss about Spring service creation here
Justin

You might also like: