spring和mybatis整合
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的配置
- 编写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 }