jpa与spring整合

1:在Pom.xml中引入Spring框架

      xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

         4.0.0

     

         com.dfrz

         Jpa_02

         0.0.1

         jar

     

         Jpa_02

         http://maven.apache.org

     

        

           

                UTF-8

           

            4.2.6.RELEASE

        

     

        

           

                com.driver

                sqlserver

               2005

           

           

                org.apache.openjpa

                openjpa-all

                2.2.0

           

           

           

                org.springframework

                spring-context

                ${spring.version}

           

           

                org.springframework

                spring-orm

                ${spring.version}

           

     

           

                org.springframework

                spring-instrument

                ${spring.version}

           

        

     

 

2:Spring整合

 

   Jpa:EntityManagerFactory---->EntityManager    

  

   Hibernate:SessionFactory---->Session

  

  

3:applicationContext.xml的配置

   xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xmlns:context="http://www.springframework.org/schema/context"

   xmlns:tx="http://www.springframework.org/schema/tx"

   xmlns:jdbc="http://www.springframework.org/schema/jdbc"

   xmlns:p="http://www.springframework.org/schema/p"

   xmlns:aop="http://www.springframework.org/schema/aop"

   xsi:schemaLocation="http://www.springframework.org/schema/beans

   http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

   http://www.springframework.org/schema/context

   http://www.springframework.org/schema/context/spring-context-3.1.xsd

    http://www.springframework.org/schema/tx

   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

    http://www.springframework.org/schema/jdbc

   http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd

   http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

 

   <context:annotation-config>context:annotation-config>

   <context:component-scan base-package="com.test">context:component-scan>

 

 

  

   <bean name="dataSource"

      class="org.springframework.jdbc.datasource.DriverManagerDataSource">

      <property name="driverClassName"

         value="com.microsoft.sqlserver.jdbc.SQLServerDriver">

      property>

      <property name="url"

         value="jdbc:sqlserver://127.0.0.1:1433;databaseName=Java1503">

      property>

      <property name="username" value="sa">property>

      <property name="password" value="">property>

   bean>

 

 

   <bean name="entityManagerFactory"

      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

      <property name="persistenceProviderClass"

         value="org.apache.openjpa.persistence.PersistenceProviderImpl">

      property>

      <property name="packagesToScan" value="com.jpa.entity">

      property>

      <property name="jpaProperties">

         <props>

            <prop key="javax.persistence.jdbc.driver">

                com.microsoft.sqlserver.jdbc.SQLServerDriver

            prop>

            <prop key="javax.persistence.jdbc.url">

               jdbc:sqlserver://localhost:1433;DatabaseName=java1411;SelectMethod=cursor;

            prop>

            <prop key="javax.persistence.jdbc.user">saprop>

            <prop key="javax.persistence.jdbc.password">prop>

            <prop key="openjpa.jdbc.SynchronizeMappings">

                buildSchema(ForeignKeys=true)

            prop>

            <prop key="openjpa.Log">SQL=TRACEprop>

            <prop key="openjpa.ConnectionFactoryProperties">

                PrettyPrint=true,PrettyPrintLineLength=72

            prop>

           

            <prop key="openjpa.ClassLoadEnhancement">falseprop>

            <prop key="openjpa.DynamicEnhancementAgent">falseprop>

            <prop key="openjpa.RuntimeUnenhancedClasses">

                supported

            prop>

 

         props>

      property>

   bean>

 

   <bean name="transactionManager"

      class="org.springframework.orm.jpa.JpaTransactionManager">

      <property name="entityManagerFactory"

         ref="entityManagerFactory">

      property>

   bean>

   <tx:annotation-driven transaction-manager="transactionManager" />

 

beans>

4:事务归jpa控制。

/**

 * 事务归jpa控制。

 *

 * @author ctd

 *

 */

@Service

public classTestMain_2 {

   @Autowired

   private EntityManagerFactoryfactory;

 

   public EntityManagerFactorygetFactory() {

      return factory;

   }

 

   public void setFactory(EntityManagerFactoryfactory) {

      this.factory = factory;

   }

 

   /**

    * jpaSpring结合的过程中。如果事务归jpa控制。

    *

    * 那么在方法互相调用中。EntityManager由于是用factory.createEntityManager来创建的

    *

    * 类似(hibernatesession =SessionFactory.openSession)

    *

    * 因此不同的方法中,获取的manager不是同一个对象。那么事务就不是相同的事务。

    *

    * 无法保证方法互相调用中事务的统一。

    *

    * 要保证事务的统一:

    *

    * 1:使用Spring的声明式事务来统一控制。jpa中不使用事务。

    *

    * 2:不使用Spring的声明式事务来控制,那么在方法调用过程中,要进行事务对象的传递。

    *

    *

    * @return

    */

   public boolean saveUser() {

      EntityManagermanager = null;

      EntityTransactiontx = null;

      boolean flag = false;

      try {

         manager= factory.createEntityManager();

         System.out.println("manager_1 = "+ manager);

         tx= manager.getTransaction();

         tx.begin();

 

         GroupBeangroupBean = newGroupBean();

         groupBean.setGroupid(new Integer(1));

         groupBean.setGroupname("java");

 

         GroupUseruser_1 = newGroupUser();

         user_1.setUserid(new Integer(10));

         user_1.setUsername("用户1");

         user_1.setGroupBean(groupBean);

 

         GroupUseruser_2 = newGroupUser();

         user_2.setUserid(new Integer(20));

         user_2.setUsername("用户2");

         user_2.setGroupBean(groupBean);

 

         manager.persist(groupBean);

         manager.persist(user_1);

         int i = 10/0;

         manager.persist(user_2);

 

         tx.commit();

      }catch(Exception e) {

         e.printStackTrace();

         tx.rollback();

      }

      return flag;

   }

 

   public static void main(String[] args) {

      ApplicationContextcontext = newClassPathXmlApplicationContext(

            "applicationContext.xml");

 

      TestMain_2testMain_2 = (TestMain_2) context.getBean("testMain_2");

 

      testMain_2.saveUser();

   }

 

}

 

5:事务归Spring控制。

 

      5.1:在配置文件中打开声明式事务的注解。

     

         class="org.springframework.orm.jpa.JpaTransactionManager">

        

            ref="entityManagerFactory">

        

     

     

     

      5.2:在代码中控制事务:

/**

 * 事务归Spring声明式事务控制。

 *

 * @author ctd

 *

 */

@Service

@Transactional

public classTestMain_3 {

   @PersistenceContext

   /**

    * @PersistenceContext,将创建的EntityManager放到上下文对象中。

    *

    * 达到EntityManager在方法中共享效果 ==类似于Hibernate中的getCurrentSession的操作。

    */

   private EntityManager manager;

 

   public EntityManagergetEntityManager() {

      return manager;

   }

 

   public void setEntityManager(EntityManagermanager) {

      this.manager = manager;

   }

 

   @Autowired

   private UserDAO userdao;

  

  

 

   /**

    * 方法要受到声明式事务的管理:必须声明为public类型。

    *

    * @return

    */

   public boolean saveGroup() {

      boolean flag = false;

      try {

         System.out.println("saveGroup--->manager = " + manager);

 

         GroupBeangroupBean = newGroupBean();

         groupBean.setGroupid(new Integer(1));

         groupBean.setGroupname("java");

         manager.persist(groupBean);

 

         // 测试:相同类中相同的方法,事务是否一致性。

         // this.saveUser();

 

         // 测试:不同类中方法的调用,事务是否一致性

         userdao.saveUser();

      }catch(Exception e) {

         e.printStackTrace();

         throw new RuntimeException(e);

      }

      return flag;

   }

 

   public void saveUser() {

      System.out.println("saveUser--->manager = " + manager);

      GroupBeangroupBean = (GroupBean) manager.find(GroupBean.class,

            new Integer(1));

      GroupUseruser_1 = newGroupUser();

      user_1.setUserid(new Integer(10));

      user_1.setUsername("用户1");

      user_1.setGroupBean(groupBean);

 

      GroupUseruser_2 = newGroupUser();

      user_2.setUserid(new Integer(20));

      user_2.setUsername("用户2");

      user_2.setGroupBean(groupBean);

 

      manager.persist(user_1);

      int i = 10 / 0;

 

      manager.persist(user_2);

   }

 

   public static void main(String[] args) {

      ApplicationContextcontext = newClassPathXmlApplicationContext(

            "applicationContext.xml");

 

      TestMain_3testMain_3 = (TestMain_3) context.getBean("testMain_3");

 

      testMain_3.saveGroup();

   }

 

}

  

   

  

 

 

你可能感兴趣的:(javaweb)