1. 程式人生 > >spring和mybatis整合

spring和mybatis整合

ans int idle iso face 整合 testin pac 主配置文件

1 spring和mybatis整合

1.1 整合思路

需要spring通過單例方式管理SqlSessionFactory。

持久層的mapper都需要由spring進行管理。

整合步驟:

u 基本環境的配置

  • 創建項目
  • 導入相關jar文件
  • 創建相關包路徑、pojo

u Dao的配置(此處使用MyBatis代理接口的方式)

  • 編寫MyBatis主配置文件
  • spring配置文件的整合
  • MyBatis映射文件和Dao接口(及XXXMapper.java)的編寫

u service的配置

  • 編寫service接口和其實現類
  • Spring對service管理的配置文件

1.2 基本環境配置

創建一個新的java(或者web)工程

jar包:

  • mybatis3.2.7的jar包
  • spring3.2.0的jar包(包括:aopalliance-1.0.jar和aspectjweaver-1.6.11.jar)
  • mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,mybatis和spring整合由mybatis提供。

mybatis-spring-1.2.2.jar

全部jar包:

技術分享圖片

工程結構:

技術分享圖片

applicationContext.xml spring配置文件

 1 <?
xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 8 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 9 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 10 11 </beans>

SqlMapperConfig.xml mybatis配置文件

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
4 <configuration>
5 
6 </configuration>

Log4j.properties 日誌文件

1 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
2 log4j.appender.stdout.Target=System.out
3 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
4 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c{1}:%L - %m%n
5 #在開發環境下日誌級別要設置成DEBUG,生產環境設置成info或error
6 log4j.rootLogger=DEBUG, stdout

db.properties 數據庫配置文件

1 driver=oracle.jdbc.OracleDriver
2 url=jdbc:oracle:thin:@localhost:1521:xe
3 user=zhou
4 pwd=123456

1.3 Dao的配置

1.編寫MyBatis主配置文件SqlMapperConfig.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5     <settings>
 6         <!-- 打印查詢語句 -->
 7         <setting name="logImpl" value="STDOUT_LOGGING" />
 8     </settings>
 9     <typeAliases>
10         <!--通過package, 可以直接指定package的名字, mybatis會自動掃描你指定包下面的javabean, 並且默認設置一個別名,默認的名字為: 
11             javabean 的首字母小寫的非限定類名來作為它的別名。 也可在javabean 加上註解@Alias 來自定義別名, 例如: @Alias(user) -->
12         <package name="cn.inspur.domain" />
13     </typeAliases>
14         <!-- applicationcontext.xml中已做配置,全部交與spring容器管理 -->
15 <!--     <environments default="test"> 
16          <environment id="test"> 
17              <transactionManager type="JDBC"> 
18              </transactionManager> 
19              <dataSource type="POOLED"> 
20                  <property name="driver" value="${driver}" /> 
21                  <property name="url" value="${url}" /> 
22                  <property name="username" value="${user}" /> 
23                  <property name="password" value="${pwd}" /> 
24              </dataSource> 
25          </environment> 
26      </environments> -->
27 <!-- spring的applicationcontext.xml中已做了掃描配置;但有些規則需要遵守
28         1.XXXmapper.xml文件必須與XXXmapper.java(dao接口)同名;
29         2.XXXmapper.xml文件必須與XXXmapper.java(dao接口)放在同一目錄;
30  -->
31 <!--     <mappers> 
32          <package name="cn.inspur.bbs.mapper"/> 
33      </mappers> -->
34 </configuration>

2.spring配置文件的整合applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 8     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
 9     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
10 
11     <!-- 自動加載db.properties,供dataSource獲取 -->
12     <context:property-placeholder location="classpath:db.properties" />
13     <!-- spring中配置Session工廠類,去讀取mybatis的主配置文件 -->
14     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
15         <property name="configLocation" value="classpath:mybatis/SqlMapperConfig.xml"></property>
16         <property name="dataSource" ref="dataSource"></property>
17     </bean>
18     <!-- 配置dataSource數據源,及mybatis自帶的數據庫連接池,也可以使用第三方連接池,如c3p0,druid等 -->
19     <bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource">
20         <property name="driver" value="${driver}"></property>
21         <property name="url" value="${url}"></property>
22         <property name="username" value="${user}"></property>
23         <property name="password" value="${pwd}"></property>
24         <property name="poolMaximumActiveConnections" value="3"></property>
25         <property name="poolMaximumIdleConnections" value="1"></property>
26     </bean>
27     <!-- 雖然mybatis自帶事務管理類,但與spring整合後建議使用spring的事務管理類,將主動權交與spring管理 -->
28     <bean id="dtm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
29         <property name="dataSource" ref="dataSource"></property>
30     </bean>
31     <!-- 雖然可以在mybatiscfg.xml通過mappers節點來配置所有mapper文件,但非常麻煩;
32     借助MapperScannerConfigurer類可以自動掃描所有mapper映射文件,而不用在mybatiscfg.xml逐個添加;
33     如果需要掃描多個包,以半角逗號分割 -->
34     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
35         <property name="basePackage" value="cn.inspur.mapper"></property>
36         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
37     </bean>
38 <!-- 切面配置 -->
39     <tx:advice id="txAdvice" transaction-manager="dtm">
40         <tx:attributes>
41             <tx:method name="insert*" propagation="REQUIRED"/>
42             <tx:method name="update*" propagation="REQUIRED"/>
43             <tx:method name="delete*" propagation="REQUIRED"/>
44             <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
45             <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
46             <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
47         </tx:attributes>
48     </tx:advice>
49     <aop:config>
50 <!-- 切點表示切所有service類 -->
51         <aop:pointcut expression="execution(* *..*Service.*(..))" id="cut"/>
52         <aop:advisor advice-ref="txAdvice"  pointcut-ref="cut"/>
53     </aop:config>
54 </beans>

3.MyBatis映射文件和Dao接口(即XXXMapper.java)的編寫

StudentMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="cn.inspur.mapper.StudentMapper">
 6 
 7     <resultMap type="student" id="studentMap">
 8         <id column="stu_id" property="stuId" />
 9         <result column="stu_name" property="stuName" />
10         <result column="stu_birthdate" property="stuBirthdate" />
11         <result column="stu_phone" property="stuPhone" />
12     </resultMap>
13 
14     <sql id="studentColumn">
15         stu_id,stu_name,stu_birthdate,stu_phone
16     </sql>
17 
18     <select id="selectAllStudent" resultMap="studentMap">
19         select
20         <include refid="studentColumn" />
21         from student
22     </select>
23 
24     <select id="selectStudentById" resultMap="studentMap" parameterType="java.lang.Integer">
25         select
26         <include refid="studentColumn" />
27         from student
28         where 1=1
29         <if test="#{stuId}!=null">
30             and stu_id=#{stuId}
31         </if>
32     </select>
33 
34     <insert id="insertStudent" parameterType="student">
35         insert into
36         student(stu_id,stu_name,stu_birthdate,stu_phone)
37         values(seqstu.nextval,#{stuName},#{stuBirthdate},#{stuPhone})
38     </insert>
39 </mapper>

StudentMapper.java

 1 package cn.inspur.mapper;
 2 
 3 import java.util.List;
 4 
 5 import cn.inspur.domain.Student;
 6 
 7 public interface StudentMapper {
 8     public void insertStudent(Student s);
 9     public void updateStudent(Student s);
10     public void deleteStudent(int stuId);
11     public Student selectStudentById(int stuId);
12     public List<Student> selectAllStudent();
13 }

1.4 service的配置

  1. 編寫service接口和其實現類

StudentService.java

 1 package cn.inspur.service;
 2 
 3 import java.util.List;
 4 
 5 import cn.inspur.domain.Student;
 6 
 7 public interface StudentService {
 8     public void insertStudent(Student s);
 9     public void updateStudent(Student s);
10     public void deleteStudent(int stuId);
11     public Student selectStudentById(int stuId);
12     public List<Student> selectAllStudent();
13 }

StudentServiceImpl.java

 1 package cn.inspur.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 
 7 import cn.inspur.domain.Student;
 8 import cn.inspur.mapper.StudentMapper;
 9 import cn.inspur.service.StudentService;
10 
11 public class StudentServiceImpl implements StudentService{
12     @Autowired
13     StudentMapper studentMapper;
14     
15     @Override
16     public void insertStudent(Student s) {
17         studentMapper.insertStudent(s);
18     }
19 
20     @Override
21     public void updateStudent(Student s) {
22         studentMapper.updateStudent(s);
23     }
24 
25     @Override
26     public void deleteStudent(int stuId) {
27         studentMapper.deleteStudent(stuId);
28     }
29 
30     @Override
31     public Student selectStudentById(int stuId) {
32         return  studentMapper.selectStudentById(stuId);
33     }
34 
35     @Override
36     public List<Student> selectAllStudent() {
37         return studentMapper.selectAllStudent();
38     }
39 
40 }

2.Spring對service管理的配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
 8     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
 9     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
10     
11     <bean id="studentService" class="cn.inspur.service.impl.StudentServiceImpl"></bean>
12 
13 </beans>

1.5 測試

 1 package cn.inspur.test;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.List;
 5 
 6 import org.junit.Test;
 7 import org.springframework.context.ApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 
10 import cn.inspur.domain.Student;
11 import cn.inspur.service.StudentService;
12 
13 public class Demo {
14     @Test
15     public void testInsert() throws Exception{
16         ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml","classpath:spring/applicationContext_services.xml");
17         StudentService service=ctx.getBean("studentService", StudentService.class);
18         Student s=new Student();
19         s.setStuName("tom");
20         s.setStuBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse("1998-1-12"));
21         s.setStuPhone("15012344321");
22         service.insertStudent(s);
23     }
24     @Test
25     public void testSelectAll() throws Exception{
26         ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml","classpath:spring/applicationContext_services.xml");
27         StudentService service=ctx.getBean("studentService", StudentService.class);
28         
29         List<Student> list = service.selectAllStudent();
30         System.out.println(list);
31     }
32 }

spring和mybatis整合