JBoss
4.2.x Spring 3 JPA Hibernate Tutorial
by Byron
Kiourtzoglou on May
18th, 2010 | Filed
in: Enterprise
Java Tags: Eclipse, HSQLDB, JBoss, JBoss
Hibernate, JBoss
TreeCache, JGroups, JNDI, JPA, JTA, MySQL,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 :
The spring.xml file,
that drives the spring container.
The persistence.xml file,
that drives the JPA ORM layer
The
second lvl cache file e.g. treecache.xml for the
JBoss TreeCache provider (if needed)
An
example spring.xml file is presented below :
15
|
< context:component-scan base-package = "com.mycomp.mypackage" />
|
17
|
< task:annotation-driven executor = "myExecutor" scheduler = "myScheduler" />
|
19
|
< task:executor id = "myExecutor" pool-size = "5" />
|
21
|
< task:scheduler id = "myScheduler" pool-size = "10" />
|
23
|
< tx:annotation-driven />
|
25
|
< bean id = "entityManagerFactory"
|
26
|
class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
|
27
|
< property name = "persistenceUnitName" value = "MyPersistenceUnit" />
|
30
|
< bean id = "transactionManager"
|
31
|
class = "org.springframework.transaction.jta.JtaTransactionManager" >
|
32
|
< property name = "transactionManagerName" value = "java:/TransactionManager" />
|
33
|
< property name = "userTransactionName" value = "UserTransaction" />
|
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 :
08
|
< persistence-unit name = "MyPersistenceUnit" transaction-type = "JTA" >
|
10
|
< provider >org.hibernate.ejb.HibernatePersistence</ provider >
|
11
|
< jta-data-source >java:/MyDataSource</ jta-data-source >
|
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" />
|
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 :
03
|
< classpath codebase = "./lib" archives = "jboss-cache.jar,
jgroups.jar" />
|
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" >
|
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" />
|
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"
|
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 >
|
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;
|
03
|
import javax.persistence.Column;
|
04
|
import javax.persistence.Entity;
|
05
|
import javax.persistence.Id;
|
06
|
import javax.persistence.Table;
|
09
|
@Table (name
= "EMPLOYEE" )
|
10
|
public class EmployeeDTO implements java.io.Serializable
{
|
12
|
private static final long serialVersionUID
= 7440297955003302414L;
|
15
|
@Column (name= "employee_id" )
|
16
|
private long employeeId;
|
18
|
@Column (name= "employee_name" ,
nullable = false ,
length= 30 )
|
19
|
private String
employeeName;
|
21
|
@Column (name= "employee_surname" ,
nullable = false ,
length= 30 )
|
22
|
private String
employeeSurname;
|
24
|
@Column (name= "job" ,
length= 50 )
|
27
|
public EmployeeDTO()
{
|
30
|
public EmployeeDTO( int employeeId)
{
|
31
|
this .employeeId
= employeeId;
|
34
|
public EmployeeDTO( long employeeId,
String employeeName, String employeeSurname,
|
36
|
this .employeeId
= employeeId;
|
37
|
this .employeeName
= employeeName;
|
38
|
this .employeeSurname
= employeeSurname;
|
42
|
public long getEmployeeId()
{
|
46
|
public void setEmployeeId( long employeeId)
{
|
47
|
this .employeeId
= employeeId;
|
50
|
public String
getEmployeeName() {
|
54
|
public void setEmployeeName(String
employeeName) {
|
55
|
this .employeeName
= employeeName;
|
58
|
public String
getEmployeeSurname() {
|
59
|
return employeeSurname;
|
62
|
public void setEmployeeSurname(String
employeeSurname) {
|
63
|
this .employeeSurname
= employeeSurname;
|
66
|
public String
getJob() {
|
70
|
public void setJob(String
job) {
|
Following
is the DAO class for accessing Employee data (EmployeeDTO)
01
|
package com.mycomp.myproject.dao;
|
03
|
import javax.annotation.PostConstruct;
|
04
|
import javax.persistence.EntityManagerFactory;
|
06
|
import org.springframework.beans.factory.annotation.Autowired;
|
07
|
import org.springframework.stereotype.Repository;
|
09
|
import com.mycomp.myproject.dto.EmployeeDTO;
|
11
|
@Repository ( "employeeDAO" )
|
12
|
public class EmployeeDAO extends JpaDAO {
|
15
|
EntityManagerFactory
entityManagerFactory;
|
19
|
super .setEntityManagerFactory(entityManagerFactory);
|
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;
|
03
|
import java.lang.reflect.ParameterizedType;
|
04
|
import java.util.List;
|
06
|
import javax.persistence.EntityManager;
|
07
|
import javax.persistence.PersistenceException;
|
08
|
import javax.persistence.Query;
|
10
|
import org.springframework.orm.jpa.JpaCallback;
|
11
|
import org.springframework.orm.jpa.support.JpaDaoSupport;
|
13
|
public abstract class JpaDAO extends JpaDaoSupport
{
|
14
|
protected Class
entityClass;
|
16
|
@SuppressWarnings ( "unchecked" )
|
18
|
ParameterizedType
genericSuperclass = (ParameterizedType) getClass()
|
19
|
.getGenericSuperclass();
|
20
|
this .entityClass
= (Class) genericSuperclass
|
21
|
.getActualTypeArguments()[ 1 ];
|
24
|
public void persist(E
entity) {
|
25
|
getJpaTemplate().persist(entity);
|
28
|
public void remove(E
entity) {
|
29
|
getJpaTemplate().remove(entity);
|
32
|
public E
merge(E entity) {
|
33
|
return getJpaTemplate().merge(entity);
|
36
|
public void refresh(E
entity) {
|
37
|
getJpaTemplate().refresh(entity);
|
40
|
public E
findById(K id) {
|
41
|
return getJpaTemplate().find(entityClass,
id);
|
44
|
public E
flush(E entity) {
|
45
|
getJpaTemplate().flush();
|
49
|
@SuppressWarnings ( "unchecked" )
|
50
|
public List
findAll() {
|
51
|
Object
res = getJpaTemplate().execute( new JpaCallback()
{
|
53
|
public Object
doInJpa(EntityManager em) throws PersistenceException
{
|
54
|
Query
q = em.createQuery( "SELECT
h FROM " +
|
55
|
entityClass.getName()
+ "
h" );
|
56
|
return q.getResultList();
|
64
|
@SuppressWarnings ( "unchecked" )
|
65
|
public Integer
removeAll() {
|
66
|
return (Integer)
getJpaTemplate().execute( new JpaCallback()
{
|
68
|
public Object
doInJpa(EntityManager em) throws PersistenceException
{
|
69
|
Query
q = em.createQuery( "DELETE
FROM " +
|
70
|
entityClass.getName()
+ "
h" );
|
71
|
return q.executeUpdate();
|
This
tutorial concludes, with the second part, where we are going to
discuss about Spring service creation here
Justin
You
might also like:
1 comment:
ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses
Post a Comment