<p>Spring3、hibernate4、JPA配置在自己的电脑上试了下,没有找到事务管理解决的办法,今天图书馆看书,参考书里面的配置解决了事务管理问题,在此记录,顺便与诸君共享</p> <p><strong>首先是applicationContext的配置文件:</strong></p> <p><font color="#0000ff"><?xml version="1.0" encoding="UTF-8"?> <br /><beans xmlns="</font><a href="http://www.springframework.org/schema/beans""><font color="#0000ff">http://www.springframework.org/schema/beans"</font></a> <br /><font color="#0000ff">    xmlns:xsi="</font><a href="http://www.w3.org/2001/XMLSchema-instance""><font color="#0000ff">http://www.w3.org/2001/XMLSchema-instance"</font></a><font color="#0000ff"> xmlns:p="</font><a href="http://www.springframework.org/schema/p""><font color="#0000ff">http://www.springframework.org/schema/p"</font></a> <br /><font color="#0000ff">    xmlns:context="</font><a href="http://www.springframework.org/schema/context""><font color="#0000ff">http://www.springframework.org/schema/context"</font></a> <br /><font color="#0000ff">    xmlns:aop="</font><a href="http://www.springframework.org/schema/aop""><font color="#0000ff">http://www.springframework.org/schema/aop"</font></a><font color="#0000ff"> xmlns:tx="</font><a href="http://www.springframework.org/schema/tx""><font color="#0000ff">http://www.springframework.org/schema/tx"</font></a> <br /><font color="#0000ff">    xsi:schemaLocation="</font><a href="http://www.springframework.org/schema/beans"><font color="#0000ff">http://www.springframework.org/schema/beans</font></a><font color="#0000ff"> </font><a href="http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><font color="#0000ff">http://www.springframework.org/schema/beans/spring-beans-2.5.xsd</font></a><font color="#0000ff">   <br />    </font><a href="http://www.springframework.org/schema/context"><font color="#0000ff">http://www.springframework.org/schema/context</font></a><font color="#0000ff"> </font><a href="http://www.springframework.org/schema/context/spring-context-2.5.xsd"><font color="#0000ff">http://www.springframework.org/schema/context/spring-context-2.5.xsd</font></a><font color="#0000ff">   <br />    </font><a href="http://www.springframework.org/schema/aop"><font color="#0000ff">http://www.springframework.org/schema/aop</font></a><font color="#0000ff"> </font><a href="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"><font color="#0000ff">http://www.springframework.org/schema/aop/spring-aop-2.5.xsd</font></a><font color="#0000ff">   <br />    </font><a href="http://www.springframework.org/schema/tx"><font color="#0000ff">http://www.springframework.org/schema/tx</font></a><font color="#0000ff"> </font><a href="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd""><font color="#0000ff">http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"</font></a><font color="#0000ff">></font></p> <p><font color="#0000ff">    <!-- 数据源定义,使用Apache c3p0 连接池 --> <br />    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" <br />        destroy-method="close"> <br />        <property name="driverClass" value="com.mysql.jdbc.Driver" /> <br />        <property name="jdbcUrl" <br />            value="jdbc:mysql://localhost:3306/zjgcmcc?useUnicode=true&amp;characterEncoding=utf-8" /> <br />        <property name="user" value="root" /> <br />        <property name="password" value="sunkai" /> <br />        <property name="checkoutTimeout" value="5000" /> <br />        <property name="minPoolSize" value="2" /> <br />        <property name="maxPoolSize" value="10" /> <br />        <property name="maxStatements" value="100" /> <br />        <property name="acquireIncrement" value="2" /> <br />    </bean> <br />   </font><font color="#ff0000"><!-- 将 EntityManager 对象注射到标有 @PersistenceContext 的属性上 --> <br />    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <br /></font><font color="#0000ff">    <!-- EntityManagerFanctory 对象,用户产生EntityManager --> <br />    <bean id="entityManagerFactory" <br />        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" destroy-method="destroy"> <br />        <property name="dataSource" ref="dataSource" /> <br />        <property name="persistenceUnitName" value="hibernateJPA" /> <br />        <property name="jpaVendorAdapter"> <br />            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <br />                <property name="showSql" value="true" /> <br />                <property name="generateDdl" value="true" /> <br />            </bean> <br />        </property> <br />    </bean> <br />    <!-- 事务管理配置 --> <br />    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <br />        <property name="entityManagerFactory" ref="entityManagerFactory" /> <br />    </bean> <br />    <!-- 将事务管理配置到有@Trancactional 的类、方法上 <br />    <tx:annotation-driven transaction-manager="transactionManager" /> <br />     --> <br />    <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <br />        <tx:attributes> <br />            <tx:method name="add*" propagation="REQUIRED"/> <br />            <tx:method name="remove*" propagation="REQUIRED"/> <br />            <tx:method name="delete*" propagation="REQUIRED"/> <br />            <tx:method name="update*" propagation="REQUIRED"/> <br />            <tx:method name="*" propagation="SUPPORTS" read-only="true" /> <br />        </tx:attributes> <br />    </tx:advice> <br />    <aop:config> <br />        <aop:pointcut id="businessService" <br />            expression="execution(* zjgcmcc.web.service.*.*(..))" /> <br />        <aop:advisor advice-ref="transactionAdvice" pointcut-ref="businessService" /> <br />    </aop:config></font></p> <p><font color="#0000ff">    <!--引入dao、service及其他bean设置--> <br />    <import resource="beans.xml" /> <br /></beans></font></p> <p><font color="#000000"> Dao类、Service类、Controller类及其他bean配置在一个单独的beans.xml文件中:</font></p> <p><font color="#0000ff"><?xml version="1.0" encoding="UTF-8"?> <br /><beans xmlns="</font><a href="http://www.springframework.org/schema/beans""><font color="#0000ff">http://www.springframework.org/schema/beans"</font></a> <br /><font color="#0000ff">    xmlns:xsi="</font><a href="http://www.w3.org/2001/XMLSchema-instance""><font color="#0000ff">http://www.w3.org/2001/XMLSchema-instance"</font></a> <br /><font color="#0000ff">    xsi:schemaLocation="</font><a href="http://www.springframework.org/schema/beans"><font color="#0000ff">http://www.springframework.org/schema/beans</font></a><font color="#0000ff"> </font><a href="http://www.springframework.org/schema/beans/spring-beans.xsd""><font color="#0000ff">http://www.springframework.org/schema/beans/spring-beans.xsd"</font></a><font color="#0000ff">> <br />    <!-- 基于JPA的通用基础Dao --> <br />    <bean id="baseDao" class="zjgcmcc.web.dao.impl.BaseDao"></bean> <br />    <br />    <bean id="userService" class="zjgcmcc.web.service.UserService"> <br />        <property name="userDao" ref="baseDao"></property> <br />    </bean></font></p> <p><font color="#0000ff"></beans></font></p> <p><font color="#000000"><strong>此处是persistence.xml的文件配置:</strong></font></p> <p><font color="#0000ff"><?xml version="1.0"?> <br /><persistence xmlns="</font><a href="http://java.sun.com/xml/ns/persistence""><font color="#0000ff">http://java.sun.com/xml/ns/persistence"</font></a><font color="#0000ff"> version="1.0" <br />    xmlns:xsi="</font><a href="http://www.w3.org/2001/XMLSchema-instance""><font color="#0000ff">http://www.w3.org/2001/XMLSchema-instance"</font></a> <br /><font color="#0000ff">    xsi:schemaLocation="</font><a href="http://java.sun.com/xml/ns/persistence"><font color="#0000ff">http://java.sun.com/xml/ns/persistence</font></a><font color="#0000ff"> </font><a href="http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd""><font color="#0000ff">http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"</font></a><font color="#0000ff"> > <br />    <persistence-unit name="hibernateJPA" transaction-type="RESOURCE_LOCAL"> <br />        <provider>org.hibernate.ejb.HibernatePersistence</provider> <br />        <!-- entity classes --> <br />        <class>zjgcmcc.web.entity.Order</class> <br />        <class>zjgcmcc.web.entity.BaseEntity</class> <br />        <class>zjgcmcc.web.entity.TB_Dept</class> <br />        <class>zjgcmcc.web.entity.TB_User</class> <br />        <class>zjgcmcc.web.entity.TB_Role</class></font></p> <p><font color="#0000ff"><!-- 下方为hibernate的一些属性设置--></font><font color="#0000ff"> <br />        </font><font color="#0000ff"><properties> <br />            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" /> <br />            <property name="hibernate.max_fetch_depth" value="3" /> <br />            <property name="hibernate.hbm2ddl.auto" value="update" /> <br />            <property name="hibernate.jdbc.fetch_size" value="18" /> <br />            <property name="hibernate.jdbc.batch_size" value="10" /> <br />            <property name="hibernate.show_sql" value="true" /> <br />            <property name="hibernate.format_sql" value="true" /> <br />        </properties> <br />    </persistence-unit> <br /></persistence></font></p> <font color="#0000ff"> <p><font color="#000000"><strong>来看看通用的Dao类的写法:</strong></font></p> <p><font color="#000000">接口:IBaseDao.java</font></p> <p>package zjgcmcc.web.dao;</p> <p>import java.io.Serializable; <br />import java.util.List; <br />public interface IBaseDao<T,ID extends Serializable> { <br />    public T findById(T t,ID id); <br />    public List<T> query(String sql,T t); <br />    public int add(T object); <br />    public int update(T object); <br />    public int update(String sql); <br />    public int delete(T object); <br />    public void flush(); <br />}</p> <p><font color="#000000">Dao的接口实现类:BaseDao.java</font></p> <p>package zjgcmcc.web.dao.impl;</p> <p>import java.io.Serializable; <br />import java.util.List;</p> <p>import javax.persistence.EntityManager; <br />import javax.persistence.PersistenceContext;</p> <p>import zjgcmcc.web.dao.IBaseDao;</p> <p>public class BaseDao<T extends Serializable, ID extends Serializable> implements IBaseDao<T, ID> { <br />    <font color="#ff0000">@PersistenceContext <br />    private EntityManager entityManager;</font></p> <p>    @Override <br />    public T findById(T t, ID id) { <br />        // TODO Auto-generated method stub <br />        T find = (T) this.entityManager.find(t.getClass(), id); <br />        return find; <br />    }</p> <p>    @Override <br />    public List<T> query(String sql, T t) { <br />        // TODO Auto-generated method stub <br />        return this.entityManager.createNativeQuery(sql,t.getClass()) <br />                .getResultList(); <br />    }</p> <p>    @Override <br />    public int add(T object) { <br />        // TODO Auto-generated method stub <br />        int result = 1; <br />        try { <br />            this.entityManager.persist(object); <br />        } catch (Exception e) { <br />            result = 0; <br />        } <br />        return result;</p> <p>    }</p> <p>    @Override <br />    public int update(T object) { <br />        // TODO Auto-generated method stub</p> <p>        int result = 1; <br />        try { <br />            this.entityManager.merge(object); <br />        } catch (Exception e) { <br />            result = 0; <br />        } <br />        return result; <br />    }</p> <p>    @Override <br />    public int update(String sql) { <br />        // TODO Auto-generated method stub <br />        return 0; <br />    }</p> <p>    @Override <br />    public int delete(T object) { <br />        // TODO Auto-generated method stub <br />        try { <br />            this.entityManager.remove(object); <br />            return 1; <br />        } catch (Exception e) { <br />            return 0; <br />        }</p> <p>    }</p> <p>    @Override <br />    public void flush() { <br />        // TODO Auto-generated method stub <br />        this.entityManager.flush(); <br />    } <br />}</p> <p><font color="#000000"><strong>接下来是一个业务层Service类:UserService.java</strong></font></p> <p>package zjgcmcc.web.service; <br />import zjgcmcc.web.dao.impl.BaseDao; <br />import zjgcmcc.web.entity.TB_User;</p> <p>public class UserService { <br />    private BaseDao<TB_User,String> userDao; <br />    <br />    public BaseDao<TB_User, String> getUserDao() { <br />        return userDao; <br />    } <br />    public void setUserDao(BaseDao<TB_User, String> userDao) { <br />        this.userDao = userDao; <br />    }</p> <p> <br />    public void addUser(TB_User user){ <br />        this.userDao.add(user); <br />    } <br />} <br /><strong><font color="#000000">最后是一个单元测试:UserJPATest.java</font></strong></p> <p>package test; <br />import java.util.ArrayList; <br />import java.util.List; <br />import javax.persistence.EntityManager; <br />import javax.persistence.EntityManagerFactory; <br />import org.junit.Test; <br />import org.junit.runner.RunWith; <br />import org.springframework.beans.factory.annotation.Autowired; <br />import org.springframework.orm.jpa.JpaTransactionManager; <br />import org.springframework.test.context.ContextConfiguration; <br />import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <br />import zjgcmcc.web.entity.TB_Dept; <br />import zjgcmcc.web.entity.TB_Role; <br />import zjgcmcc.web.entity.TB_User; <br />import zjgcmcc.web.service.UserService;</p> <p>@RunWith(SpringJUnit4ClassRunner.class) <br />@ContextConfiguration("classpath:applicationContext.xml") <br />public class UserJPATest { <br />    @Autowired private UserService userService; <br />    @Autowired EntityManagerFactory emf; <br />    @Autowired JpaTransactionManager transactionManager; <br />    <br />    @Test public void test(){ <br />        TB_Dept dept=new TB_Dept(); <br />        TB_Role role=new TB_Role(); <br />        TB_User user=new TB_User(); <br />        <br />        dept.setD_id("03"); <br />        dept.setD_name("第三分中心"); <br />        role.setR_id("0301"); <br />        role.setR_name("主任"); <br />        role.setR_dept(dept); <br />        List<TB_Role> roles=new ArrayList<TB_Role>(); <br />        roles.add(role); <br />        user.setU_id("030100"); <br />        user.setU_name("A"); <br />        user.setU_roles(roles); <br />        System.out.println((userService==null)); <br />        this.userService.addUser(user); <br />    } <br />}</p> <p><strong><font color="#000000">三个Entity类:</font></strong></p> <p><strong>TB_Dept.java:</strong></p> <p>package zjgcmcc.web.entity; <br />import java.util.HashSet; <br />import java.util.Set;</p> <p>import javax.persistence.CascadeType; <br />import javax.persistence.Column; <br />import javax.persistence.Entity; <br />import javax.persistence.FetchType; <br />import javax.persistence.Id; <br />import javax.persistence.JoinColumn; <br />import javax.persistence.JoinTable; <br />import javax.persistence.ManyToMany; <br />import javax.persistence.ManyToOne; <br />import javax.persistence.Table;</p> <p> <br />@Entity <br />@Table(name="tb_dept") <br />public class TB_Dept extends BaseEntity{ <br />    private static final long serialVersionUID = -1844975459250411764L; <br />    @Id <br />    @Column(name="d_id") <br />    <br />    private String d_id; <br />    @Column(name="d_name") <br />    private String d_name; <br />    @Column(name="d_level",nullable=false) <br />    private int d_level;</p> <p>//getter setter略….    <br />} <br /></p> <p><strong>TB_Role.java:</strong></p> <p>package zjgcmcc.web.entity;</p> <p>import javax.persistence.CascadeType; <br />import javax.persistence.Column; <br />import javax.persistence.Entity; <br />import javax.persistence.FetchType; <br />import javax.persistence.Id; <br />import javax.persistence.JoinColumn; <br />import javax.persistence.JoinTable; <br />import javax.persistence.ManyToMany; <br />import javax.persistence.ManyToOne; <br />import javax.persistence.OneToMany; <br />import javax.persistence.OneToOne; <br />import javax.persistence.PrimaryKeyJoinColumn; <br />import javax.persistence.Table;</p> <p>@Entity <br />@Table(name="tb_role") <br />public class TB_Role extends BaseEntity{ <br />    private static final long serialVersionUID = 3618646459702991344L; <br />    @Id <br />    @Column(name="r_id") <br />    private String r_id; <br />    @Column(name="r_name") <br />    private String r_name; <br />    <br />    @ManyToOne(fetch=FetchType.EAGER,cascade={CascadeType.PERSIST}) <br />    @JoinColumn(name="dept_id",unique=true) <br />    private TB_Dept r_dept; <br /> //getter setter略…. <br />} <br /></p> <p><strong>TB_User.java:</strong></p> <p>package zjgcmcc.web.entity; <br />import java.util.ArrayList; <br />import java.util.HashSet; <br />import java.util.List;</p> <p>import java.util.Set;</p> <p>import javax.persistence.CascadeType; <br />import javax.persistence.Column; <br />import javax.persistence.Entity; <br />import javax.persistence.FetchType; <br />import javax.persistence.Id; <br />import javax.persistence.JoinColumn; <br />import javax.persistence.JoinTable; <br />import javax.persistence.ManyToMany; <br />import javax.persistence.OneToMany; <br />import javax.persistence.Table;</p> <p>@Entity <br />@Table(name="tb_user") <br />public class TB_User extends BaseEntity { <br />    private static final long serialVersionUID = 7665797019787902828L; <br />    @Id <br />    @Column(name="u_id") <br />    private String u_id; <br />    @Column(name="u_name") <br />    private String u_name; <br />    //tb_user与tb_dept的多对多关系 <br />    @ManyToMany(fetch=FetchType.EAGER,cascade={CascadeType.PERSIST}) <br />    @JoinTable( <br />                name="tb_user_role", <br />                joinColumns=@JoinColumn(name="user_id",referencedColumnName="u_id"), <br />                inverseJoinColumns=@JoinColumn(name="role_id",referencedColumnName="r_id") <br />                ) <br />    private List<TB_Role> u_roles=new ArrayList<TB_Role>(); <br />    <br />    @Column(name="u_phone") <br />    private String u_phone; <br />    @Column(name="u_passwd") <br />    private String u_passwd;</p> <p>//getter setter略…. </p> <p>} <br /></p> <p><font color="#000000">红字部分在配置的时候容易被忽略或配置错误,具体为何配置尚未研究,有达人了解欢迎指点一二 。</font></p> <p> <br /></p> <p><font color="#000000"></font> <br /></p> </font>