zoukankan      html  css  js  c++  java
  • JAP和Spring整合的三种方式详细方法

    <1>persistence.xml放到类路径下的META-INF下面 

    Xml代码  收藏代码
    1. <persistence xmlns="http://java.sun.com/xml/ns/persistence"  
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    3. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  
    4. http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"    version="1.0">  
    5.     <!--事务类型:local的还是global(JTA)的事务 -->  
    6.     <persistence-unit name="jpa_test" transaction-type="RESOURCE_LOCAL">  
    7.   
    8.     </persistence-unit>  
    9. </persistence>  


    <2>applicationContext.xml配置 

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xmlns:aop="http://www.springframework.org/schema/aop"  
    5.     xmlns:tx="http://www.springframework.org/schema/tx"  
    6.     xsi:schemaLocation="  
    7.     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
    8.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd  
    9.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
    10.     <!-- 自动装配注解Bean后置处理器 -->  
    11.     <bean   
    12.         class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  
    13.       
    14.     <!-- JPA注解Bean后置处理器 -->  
    15.     <bean  
    16.         class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />  
    17.   
    18.     <!-- 利用Spring的实体管理器工厂来创建JPA实体管理器 -->  
    19.     <bean id="entityManagerFactory"  
    20.         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
    21.         <property name="dataSource" ref="dataSource" />  
    22.         <property name="jpaVendorAdapter">  
    23.             <bean  
    24.                 class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  
    25.                 <property name="database" value="MYSQL" />  
    26.                 <property name="showSql" value="true" />  
    27.                 <!-- <property name="generateDdl" value="true" /> -->  
    28.             </bean>  
    29.         </property>  
    30.     </bean>  
    31.   
    32.     <bean id="dataSource"  
    33.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
    34.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
    35.         <property name="url" value="jdbc:mysql://localhost/test?useUnicode=true&amp;characterEncoding=UTF-8" />  
    36.         <property name="username" value="root" />  
    37.         <property name="password" value="root" />  
    38.     </bean>  
    39.       
    40.     <!--       
    41.     <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">   
    42.         <property name="jndiName">  
    43.             <value>java:comp/env/jdbc/jpa_ds</value>  
    44.         </property>   
    45.     </bean>  
    46.      -->  
    47.   
    48.     <!-- 声明一个Spring提供的JPA事务管理器,传入的参数是Spring中的实体管理器工厂 -->   
    49.     <bean id="transactionManager"  
    50.         class="org.springframework.orm.jpa.JpaTransactionManager">  
    51.         <property name="entityManagerFactory" ref="entityManagerFactory" />  
    52.     </bean>  
    53.   
    54.     <!-- 开启Spring提供的基于注解的声明式事务管理 -->  
    55.     <tx:annotation-driven transaction-manager="transactionManager" />  
    56.   
    57.     <!--    
    58.     <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">  
    59.         <property name="transactionManager">  
    60.             <ref local="transactionManager"/>  
    61.         </property>  
    62.         <property name="transactionAttributes">  
    63.             <props>  
    64.                 <prop key="insert*">PROPAGATION_REQUIRED</prop>  
    65.                 <prop key="update*">PROPAGATION_REQUIRED</prop>  
    66.                 <prop key="save*">PROPAGATION_REQUIRED</prop>  
    67.                 <prop key="add*">PROPAGATION_REQUIRED</prop>  
    68.                 <prop key="update*">PROPAGATION_REQUIRED</prop>  
    69.                 <prop key="remove*">PROPAGATION_REQUIRED</prop>  
    70.                 <prop key="delete*">PROPAGATION_REQUIRED</prop>  
    71.                 <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>  
    72.                 <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>  
    73.                 <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>  
    74.                 <prop key="change*">PROPAGATION_REQUIRED</prop>  
    75.                 <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>  
    76.             </props>  
    77.         </property>  
    78.     </bean>  
    79.       
    80.     <bean id="beanNameAutoProxyCreator"  
    81.         class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
    82.         <property name="beanNames">  
    83.             <list>  
    84.                 <value>*Service</value>  
    85.                 <value>*Dao</value>  
    86.             </list>  
    87.         </property>  
    88.         <property name="interceptorNames">  
    89.             <list>  
    90.                 <value>transactionInterceptor</value>  
    91.             </list>  
    92.         </property>  
    93.     </bean>              
    94.     -->  
    95.       
    96.     <!-- 直接使用Spring的 JpaTemplate -->  
    97.     <bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">  
    98.         <property name="entityManagerFactory" ref="entityManagerFactory" />  
    99.     </bean>  
    100.   
    101.     <bean id="personDao" class="quickstart.dao.impl.PersonDaoImpl" autowire="byName"/>  
    102.       
    103.     <bean id="peopleService" class="quickstart.service.impl.PeopleServiceImpl"/>  
    104. </beans>  


    <3>web.xml文件 

    Xml代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app version="2.4"   
    3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
    4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
    7.   
    8.     <display-name>jpa_test</display-name>  
    9.   
    10.     <context-param>  
    11.         <param-name>contextConfigLocation</param-name>  
    12.         <param-value>  
    13.             classpath:applicationContext.xml  
    14.         </param-value>  
    15.     </context-param>  
    16.       
    17.     <listener>  
    18.         <listener-class>  
    19.             org.springframework.web.context.ContextLoaderListener  
    20.         </listener-class>  
    21.     </listener>  
    22.       
    23.     <!-- 配置字符编码过滤器 -->     
    24.     <filter>     
    25.         <filter-name>encoding</filter-name>     
    26.         <filter-class>     
    27.             org.springframework.web.filter.CharacterEncodingFilter     
    28.         </filter-class>     
    29.         <init-param>     
    30.             <param-name>encoding</param-name>     
    31.             <param-value>UTF-8</param-value>     
    32.         </init-param>     
    33.     </filter>     
    34.          
    35.     <filter-mapping>     
    36.         <filter-name>encoding</filter-name>     
    37.         <url-pattern>/*</url-pattern>     
    38.     </filter-mapping>     
    39.   
    40.     <welcome-file-list>  
    41.         <welcome-file>index.jsp</welcome-file>  
    42.     </welcome-file-list>  
    43.       
    44. </web-app>  


    <4>泛型dao定义 

    Java代码  收藏代码
    1. public interface GenericDao<T, ID extends Serializable> {  
    2.     public T save(T entity);  
    3.   
    4.     public T update(T entity);  
    5.   
    6.     public Integer updateBySql(final String sql);  
    7.       
    8.     public void delete(T entity);  
    9.       
    10.     public T findById(ID id);  
    11.       
    12.     public List findByJPQL(String jpql);  
    13.       
    14.     public List findBySQL(String sql);  
    15.       
    16.     public List findAll();  
    17.       
    18.     public int findRowCount();  
    19. }  
    Java代码  收藏代码
      1. public class GenericDaoImpl<T, ID extends Serializable> extends JpaDaoSupport  
      2.         implements GenericDao<T, ID> {  
      3.   
      4.     private Class persistentClass;  
      5.   
      6.     public GenericDaoImpl() {  
      7.         this.persistentClass = (Class) ((ParameterizedType) getClass()  
      8.                 .getGenericSuperclass()).getActualTypeArguments()[0];  
      9.     }  
      10.   
      11.     public Class getPersistentClass() {  
      12.         return persistentClass;  
      13.     }  
      14.   
      15.     public T save(Object entity) {  
      16.         getJpaTemplate().persist(entity);  
      17.         return (T)entity;  
      18.     }  
      19.   
      20.     public T update(Object entity) {  
      21.         getJpaTemplate().merge(entity);  
      22.         return (T)entity;  
      23.     }  
      24.   
      25.     public Integer updateBySql(final String sql){  
      26.         return (Integer)getJpaTemplate().execute(new JpaCallback(){  
      27.             public Integer doInJpa(EntityManager em) throws PersistenceException{  
      28.                 return em.createNativeQuery(sql).executeUpdate();  
      29.             }  
      30.         });  
      31.     }  
      32.   
      33.     public void delete(Object entity) {  
      34.         getJpaTemplate().remove(entity);  
      35.     }  
      36.       
      37.     public T findById(Serializable id) {  
      38.         return (T)getJpaTemplate().find(this.getPersistentClass(), id);  
      39.     }  
      40.   
      41.          //要立即抓取时用"JOIN FETCH"  
      42.     public List findByJPQL(String jpql) {  
      43.         return getJpaTemplate().find(jpql);  
      44.     }  
      45.   
      46.     /** 
      47.      * 返回:list中装入的是对象数组(Object[]) 
      48.      */  
      49.     public List findBySQL(final String sql) {  
      50.         return  getJpaTemplate().executeFind(new JpaCallback(){  
      51.             public List doInJpa(EntityManager em) throws PersistenceException{  
      52.                 return em.createNativeQuery(sql).getResultList();  
      53.             }  
      54.         });  
      55.     }  
      56.   
      57.     public List findAll() {  
      58.         return getJpaTemplate().executeFind(new JpaCallback() {  
      59.             public Object doInJpa(EntityManager em) throws PersistenceException {  
      60.                 StringBuffer jpql = new StringBuffer("from ");  
      61.                 jpql.append(getPersistentClass().getName());  
      62.                 jpql.append(" obj");  
      63.                 return em.createQuery(jpql.toString()).getResultList();  
      64.             }  
      65.         });  
      66.     }  
      67.   
      68.       
      69.     public int findRowCount() {  
      70.         return ((Long) getJpaTemplate().execute(new JpaCallback() {  
      71.             public Object doInJpa(EntityManager em) throws PersistenceException {  
      72.                 StringBuffer strBuff = new StringBuffer("select count(*) from ");  
      73.                 strBuff.append(getPersistentClass().getName());  
      74.                 return em.createQuery(strBuff.toString()).getResultList().get(0);  
      75.             }  
      76.         })).intValue();  
      77.     }  
      78.       
      79. }  
  • 相关阅读:
    POJ 2418 Hardwood Species
    用Excel打开csv格式文件并生成相应图形
    虚拟内存(Virtual Memory)
    POJ 3984 迷宫问题 (Dijkstra)
    算法导论16.22 01背包问题
    POJ 1019 Number Sequence
    POJ 1458 Common Subsequence (最长公共子序列)
    Java处理文件BOM头的方式推荐
    web开发中的中文编码问题
    struts2学习笔记之spring整合
  • 原文地址:https://www.cnblogs.com/zhaowancheng/p/5852214.html
Copyright © 2011-2022 走看看