zoukankan      html  css  js  c++  java
  • spring整合jpa

    有点类似SSH整合,O(∩_∩)O哈哈~

     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:context="http://www.springframework.org/schema/context"
     5     xmlns:tx="http://www.springframework.org/schema/tx"
     6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
     8         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
     9 
    10     <!-- 配置自动扫描的包 -->
    11     <context:component-scan base-package="com.xt.jpa"></context:component-scan>
    12 
    13     <!-- 配置 C3P0 数据源 -->
    14     <context:property-placeholder location="classpath:db.properties"/>
    15 
    16     <bean id="dataSource"
    17         class="com.mchange.v2.c3p0.ComboPooledDataSource">
    18         <property name="user" value="${jdbc.user}"></property>
    19         <property name="password" value="${jdbc.password}"></property>
    20         <property name="driverClass" value="${jdbc.driverClass}"></property>
    21         <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>    
    22         
    23         <!-- 配置其他属性 -->
    24     </bean>
    25     
    26     <!-- 配置 EntityManagerFactory -->
    27     <bean id="entityManagerFactory"
    28         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    29         <property name="dataSource" ref="dataSource"></property>
    30         <!-- 配置 JPA 提供商的适配器. 可以通过内部 bean 的方式来配置 -->
    31         <property name="jpaVendorAdapter">
    32             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
    33         </property>    
    34         <!-- 配置实体类所在的包 -->
    35         <property name="packagesToScan" value="com.xt.jpa.spring.entities"></property>
    36         <!-- 配置 JPA 的基本属性. 例如 JPA 实现产品的属性 -->
    37         <property name="jpaProperties">
    38             <props>
    39                 <prop key="hibernate.show_sql">true</prop>
    40                 <prop key="hibernate.format_sql">true</prop>
    41                 <prop key="hibernate.hbm2ddl.auto">update</prop>
    42             </props>
    43         </property>
    44     </bean>
    45     
    46     <!-- 配置 JPA 使用的事务管理器 -->
    47     <bean id="transactionManager"
    48         class="org.springframework.orm.jpa.JpaTransactionManager">
    49         <property name="entityManagerFactory" ref="entityManagerFactory"></property>    
    50     </bean>
    51     
    52     <!-- 配置支持基于注解是事务配置 -->
    53     <tx:annotation-driven transaction-manager="transactionManager"/>
    54 
    55 </beans>

    dao:

     1 package com.xt.jpa.dao;
     2 
     3 import javax.persistence.EntityManager;
     4 import javax.persistence.PersistenceContext;
     5 
     6 import org.springframework.stereotype.Repository;
     7 
     8 import com.xt.jpa.spring.entities.Person;
     9 
    10 @Repository
    11 public class PersonDao {
    12 
    13     //如何获取到和当前事务关联的 EntityManager 对象呢 ?
    14     //通过 @PersistenceContext 注解来标记成员变量!
    15     @PersistenceContext
    16     private EntityManager entityManager;
    17     
    18     public void save(Person person){
    19         entityManager.persist(person);
    20     }
    21     
    22 }

    导入的包就是整合SSH用到的包

    感觉jpa的实现类在这个里头咯

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    说明出处: https://www.cnblogs.com/caijh/p/7755479.html

    还有一篇感觉也写得挺好的,比较美观,O(∩_∩)O哈哈~

    https://www.cnblogs.com/xujian2014/p/5282335.html#_label0

    Spring整合配置Mybatis

      spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位。一般需要具备如下几个基本配置。

      1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置)

    复制代码
     1    <!-- 导入properties配置文件 -->
     2     <context:property-placeholder location="classpath*:/jdbc.properties"/>
     3 
     4     <!-- 数据源基本配置 -->
     5     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     6          <property name="username" value="${jdbc.username}"/>
     7          <property name="password" value="${jdbc.password}"/>
     8          <property name="url" value="${jdbc.url}"/>
     9          <property name="driverClassName" value="${jdbc.driverClassName}"/>
    10     </bean>
    复制代码

       我们将参数配置统一写入jdbc.properties文件中:

    1 jdbc.url=jdbc:mysql://localhost:3306/mydb
    2 jdbc.driverClassName=com.mysql.jdbc.Driver
    3 jdbc.username=root
    4 jdbc.password=root

      2.配置SessionFactory(用于将数据源和mybatis的mapper映射文件进行管理和初始化)

    1    <!-- 创建sessionFactory -->
    2     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    3         <property name="dataSource" ref="dataSource"/>
    4         <!-- 扫描mapper映射文件 -->
    5         <property name="mapperLocations" value="classpath*:dao/mapping/*.xml" />
    6     </bean>

      3.扫描mapper映射文件所对应的dao接口类(其实dao接口的是实现类就是mapper.xml映射文件,此配置是为了将接口和映射文件进行初始化)

    1    <!-- 扫描与mapper映射文件对应的dao接口类 -->
    2     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    3         <property name="basePackage" value="dao.daoInterface"/>
    4         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    5     </bean>

      4.创建事务(事务有两种配置方式:注解方式和aop切入方式)

    1   <!-- 创建事务管理 -->
    2     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    3         <property name="dataSource" ref="dataSource"/>
    4     </bean>

      创建好事务管理后,我们可以选择使用注解方式实现管理,或者aop织入管理

        4.1注解方式

    1 <!-- 注解式事务配置,启动事务注解驱动 -->
    2 <tx:annotation-driven/>

        注解配置方式要先通过配置文件启动事务注解驱动,然后在要加事务的方法上面加上事务注解:@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED) 事务相关知识可参考:http://www.cnblogs.com/caijh/p/7724964.html

    复制代码
    1   @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    2     @Override
    3     public void insertUser(UserEntity userEntity) {
    4         for(int i=0;i<10;i++){
    5             userEntity.setId(111+i);
    6             userEntity.setUsername("mybatis "+i);
    7             userDao.insertUser(userEntity);
    8         }
    9     }
    复制代码

        4.2 AOP织入方式

    复制代码
     1 <!-- aop切入式事务配置 -->
     2     <tx:advice id="trAdvice" transaction-manager="transactionManager">
     3         <tx:attributes>
     4             <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
     5         </tx:attributes>
     6     </tx:advice>
     7 
     8     <aop:config>
     9         <aop:pointcut id="serviceAdvice" expression="execution(* service.serviceImpl.*.*(..))"/>
    10         <aop:advisor advice-ref="trAdvice" pointcut-ref="serviceAdvice"/>
    11     </aop:config>
    复制代码

      AOP相关知识可参考:http://www.cnblogs.com/caijh/p/7710725.html

    最终配置如下:

      

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!--
     3   ~ @(#) applicationContext.xml
     4   ~ <br> Copyright:  Copyright (c) 2017
     5   ~ <br> @author cjh
     6   ~ <br> 2017-10-29 15:45:16
     7   -->
     8 <beans xmlns="http://www.springframework.org/schema/beans"
     9        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    10        xmlns:tx="http://www.springframework.org/schema/tx"
    11        xmlns:aop="http://www.springframework.org/schema/aop"
    12        xmlns:context="http://www.springframework.org/schema/context"
    13        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    14        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    15        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.3.xsd
    16        http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    17 
    18     <!-- 导入properties配置文件 -->
    19     <context:property-placeholder location="classpath*:/jdbc.properties"/>
    20 
    21     <!-- 扫描注解包 -->
    22     <context:component-scan base-package="dao.daoInterface"/>
    23     <context:component-scan base-package="service.serviceImpl" />
    24 
    25     <!-- 数据源基本配置 -->
    26     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    27          <property name="username" value="${jdbc.username}"/>
    28          <property name="password" value="${jdbc.password}"/>
    29          <property name="url" value="${jdbc.url}"/>
    30          <property name="driverClassName" value="${jdbc.driverClassName}"/>
    31     </bean>
    32 
    33     <!-- 创建sessionFactory -->
    34     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    35         <property name="dataSource" ref="dataSource"/>
    36         <!-- 扫描mapper映射文件 -->
    37         <property name="mapperLocations" value="classpath*:dao/mapping/*.xml" />
    38     </bean>
    39 
    40     <!-- 扫描与mapper映射文件对应的dao接口类 -->
    41     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    42         <property name="basePackage" value="dao.daoInterface"/>
    43         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    44     </bean>
    45 
    46 
    47     <!-- 创建事务管理 -->
    48     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    49         <property name="dataSource" ref="dataSource"/>
    50     </bean>
    51 
    52     <!-- 注解式事务配置,启动事务注解驱动 -->
    53     <!--<tx:annotation-driven/>-->
    54 
    55     <!-- aop切入式事务配置 -->
    56     <tx:advice id="trAdvice" transaction-manager="transactionManager">
    57         <tx:attributes>
    58             <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
    59         </tx:attributes>
    60     </tx:advice>
    61 
    62     <aop:config>
    63         <aop:pointcut id="serviceAdvice" expression="execution(* service.serviceImpl.*.*(..))"/>
    64         <aop:advisor advice-ref="trAdvice" pointcut-ref="serviceAdvice"/>
    65     </aop:config>
    66 
    67 </beans>

       SSMDemo整合配置源码位置:https://gitee.com/codecaijh/SSMDemo

    Spring整合配置Hibernate

      Spring整合配置hibernate和Mybatis的配置大同小异,主要区别在与SessionFactory和映射文件的管理配置,但目的都是一样的。

      1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置)【同Mybatis配置】

      2.配置SessionFactory(因为Hibernate对数据库操作做了封装,所以需要一些额外的属性配置)

     1 <!-- 创建sessionFactory -->
     2     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
     3         <property name="dataSource" ref="dataSource"/>
     4         <property name="hibernateProperties">
     5             <props>
     6                 <prop key="hibernate.show_sql">true</prop>
     7                 <prop key="hibernate.format_sql">true</prop>
     8                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
     9                 <!--<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>-->
    10             </props>
    11         </property>
    12         <!-- 实体类映射文件 -->
    13         <property name="mappingLocations">
    14             <list>
    15                 <value>classpath*:/domain/*.hbm.xml</value>
    16             </list>
    17         </property>
    18         <!-- 扫描实体类包 -->
    19         <property name="packagesToScan">
    20             <value>domain</value>
    21         </property>
    22         <!-- 实体类 -->
    23         <property name="annotatedClasses">
    24             <list>
    25                 <value>domain.UserEntity</value>
    26             </list>
    27         </property>
    28     </bean>

      Hibernate的配置中,把映射文件和是实体类映射全部配置在SessionFactory中,也就是和Mybatis第2步和第3步类似,

      3.创建事务(事务有两种配置方式:注解方式和aop切入方式)【同Mybatis配置】

      最终配置如下:

      

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!--
     3   ~ @(#) applicationContext.xml
     4   ~ <br> Copyright:  Copyright (c) 2017
     5   ~ <br> @author cjh
     6   ~ <br> 2017-10-29 15:45:16
     7   -->
     8 <beans xmlns="http://www.springframework.org/schema/beans"
     9        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    10        xmlns:tx="http://www.springframework.org/schema/tx"
    11        xmlns:aop="http://www.springframework.org/schema/aop"
    12        xmlns:context="http://www.springframework.org/schema/context"
    13        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    14        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    15        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    16        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    17 
    18     <!-- 导入properties配置文件 -->
    19     <context:property-placeholder location="classpath*:/jdbc.properties"/>
    20 
    21     <!-- 扫描注解包 -->
    22     <context:component-scan base-package="dao.daoImpl"/>
    23     <context:component-scan base-package="service.serviceImpl" />
    24 
    25     <!-- 数据源基本配置 -->
    26     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    27          <property name="username" value="${jdbc.username}"/>
    28          <property name="password" value="${jdbc.password}"/>
    29          <property name="url" value="${jdbc.url}"/>
    30          <property name="driverClassName" value="${jdbc.driverClassName}"/>
    31     </bean>
    32 
    33     <!-- 创建sessionFactory -->
    34     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    35         <property name="dataSource" ref="dataSource"/>
    36         <property name="hibernateProperties">
    37             <props>
    38                 <prop key="hibernate.show_sql">true</prop>
    39                 <prop key="hibernate.format_sql">true</prop>
    40                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    41                 <!--<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>-->
    42             </props>
    43         </property>
    44         <!-- 实体类映射文件 -->
    45         <property name="mappingLocations">
    46             <list>
    47                 <value>classpath*:/domain/*.hbm.xml</value>
    48             </list>
    49         </property>
    50         <!-- 扫描实体类包 -->
    51         <property name="packagesToScan">
    52             <value>domain</value>
    53         </property>
    54         <!-- 实体类 -->
    55         <property name="annotatedClasses">
    56             <list>
    57                 <value>domain.UserEntity</value>
    58             </list>
    59         </property>
    60     </bean>
    61 
    62     <!-- 创建声明式事务管理 -->
    63     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    64         <property name="sessionFactory" ref="sessionFactory"/>
    65     </bean>
    66     <!-- 事务通知(注解方式) -->
    67     <tx:annotation-driven transaction-manager="transactionManager"/>
    68 
    69     <!-- 事务通知(aop方式) -->
    70     <!--<tx:advice id="txAdvice" transaction-manager="transactionManager">
    71         <tx:attributes>
    72             &lt;!&ndash; propagation配置传播行为,isolation配置隔离方式 &ndash;&gt;
    73             <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED" />
    74         </tx:attributes>
    75     </tx:advice>
    76 
    77     &lt;!&ndash; aop织入通知 &ndash;&gt;
    78     <aop:config>
    79         <aop:pointcut id="serviceOption" expression="(execution(* service.serviceImpl.*.*(..)) and (execution(* dao.daoImpl.*.*(..))))"/>
    80         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOption"/>
    81     </aop:config>-->
    82 
    83 
    84 </beans>

      SSHDemo整合配置源码位置:https://gitee.com/codecaijh/SSHDemo

    三、可能遇到的问题

      在整合mybatis的时候可能会遇到 BindingException: Invalid bound statement (not found): dao.daoInterface.UserDao.getUserInfo dao接口类和mapper文件绑定失败而找不到实现方法的异常。

      

       查看target目录下的classes文件时发现没有任何xml文件,推断项目编译的时候可能没把它包含进去。

      解决办法:

      在pom.xml文件中添加如下内容:(表示让maven将以xml和properties等为后缀的文件在构建的时候从资源路径加载到目标路径)

     1 <build>
     2     
     3       <resources>
     4           <resource>
     5               <directory>src/main/java</directory>
     6               <includes>
     7                   <include>**/*.properties</include>
     8                   <include>**/*.xml</include>
     9               </includes>
    10               <filtering>false</filtering>
    11           </resource>
    12       </resources>
    13   </build>

      资源往往不是代码,无需编译,而是一些properties或XML配置文件,构建过程中会往往会将资源文件从源路径复制到指定的目标路径。

     配置说明

    • resources,build过程中涉及的资源文件
      • targetPath,资源文件的目标路径
      • filtering,构建过程中是否对资源进行过滤,默认false
      • directory,资源文件的路径,默认位于${basedir}/src/main/resources/目录下
      • includes,一组文件名的匹配模式,被匹配的资源文件将被构建过程处理
      • excludes,一组文件名的匹配模式,被匹配的资源文件将被构建过程忽略。同时被includes和excludes匹配的资源文件,将被忽略。
    • filters,给出对资源文件进行过滤的属性文件的路径,默认位于${basedir}/src/main/filters/目录下。属性文件中定义若干键值对。在构建过程中,对于资源文件中出现的变量(键),将使用属性文件中该键对应的值替换。
    • testResources,test过程中涉及的资源文件,默认位于${basedir}/src/test/resources/目录下。这里的资源文件不会被构建到目标构件中
  • 相关阅读:
    noi 2011 noi嘉年华 动态规划
    最小乘积生成树
    noi 2009 二叉查找树 动态规划
    noi 2010 超级钢琴 划分树
    noi 2011 阿狸的打字机 AC自动机
    noi 2009 变换序列 贪心
    poj 3659 Cell Phone Network 动态规划
    noi 2010 航空管制 贪心
    IDEA14下配置SVN
    在SpringMVC框架下建立Web项目时web.xml到底该写些什么呢?
  • 原文地址:https://www.cnblogs.com/But-you/p/10483255.html
Copyright © 2011-2022 走看看