您现在的位置是:首页 >其他 >第六章 Spring整合Mybatis网站首页其他
第六章 Spring整合Mybatis
简介第六章 Spring整合Mybatis
1.整合关键部分
整合关键:把相关对象(SqlSessionFactory,映射器实例的注入等)的创建、获取、对象依赖资源的注入交给Spring容器来维护和管理
整合中各自作用:MyBatis:主要是和数据库底层进行交互;Spring:所有对象的创建、对象所依赖的资源的注入、事务管理都是由spring容器来完成。
2.整合步骤
导入依赖:mybatis、spring-context、mybatis-spring、bonecp数据源、mysql、spring-jdbc、log4j
建立相关包结构:com.sm.entity、com.sm.dao、com.sm.service、com.sm.service.impl、com.sm.test
编写配置文件:spring-config.xml、mybatis-config.xml、log4j.properties spring-config.xml内容: 数据源|sqlSessionFactory|映射器|扫描支持注解的业务Bean|事务管理器|基于注解事务 mybatis-config.xml内容: 配置日志|给实体类取别名|映射文件
编码测试:启动项目-进行测试
3.具体整合实现
导入依赖
<dependencies>
<!--mybatis依赖包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--spring-context依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!--mybatis-spring依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!--bonecp数据源-->
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.8.0.RELEASE</version>
</dependency>
<!--mysql的驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--spring-jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!--junit单元测试框架依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--log4j日志记录-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
编写配置文件:spring-config.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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--配置数据源-->
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="jdbc:mysql://localhost:3306/yndx"
p:username="root" p:password="admin"/>
<!--配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml"/>
<!--注入 映射器 Mapper basePackage指定了扫描的基准包,批量产生映射器的实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="com.sm.dao"/>
<!--注入业务Bean 扫描注解定义的业务Bean-->
<context:component-scan base-package="com.sm.service.impl"/>
<!--配置事务管理器-->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<!--基于声明式注解事务支持 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--设置日志实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--为实体类取别名 -->
<typeAliases>
<!--为整个包取别名 别名为 默认为实体类首字母小写-->
<package name="com.sm.entity"/>
</typeAliases>
<!--映射器-告诉mybatis去哪里寻找sql映射文件 -->
<mappers>
<!--通过类资源路径获取 -->
<mapper resource="com/sm/dao/StudentMapper.xml"/>
</mappers>
</configuration>
log4j.properties
### u5C06log4j.propertiesu6587u4EF6u653Eu5165u6839u76EEu5F55u4E0B
### u8BBEu7F6ELoggeru8F93u51FAu7EA7u522Bu548Cu8F93u51FAu76EEu7684u5730
###
log4j.rootLogger=debug,stdout,logfile
### u628Au65E5u5FD7u4FE1u606Fu8F93u51FAu5230u63A7u5236u53F0 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
### u628Au65E5u5FD7u4FE1u606Fu8F93u51FAu5230u6587u4EF6uFF1Ajbit.log ###
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%l %F %p %m%n
编写代码:实体类
//学生类
public class Student {
private Integer sno;
private String pwd;
private String sname;
private String sex;
private Integer gid;
private Integer age;
private String phone;
private String address;
public Integer getSno() {
return sno;
}
public void setSno(Integer sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Integer getGid() {
return gid;
}
public void setGid(Integer gid) {
this.gid = gid;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
数据访问层接口
//学生映射接口
public interface StudentMapper {
@Select("select * from student where sno=#{sno}")
Student selectBySno(Integer sno); //单个参数
@Select("select * from student")
List<Student> getStulist(); //查询所有学生
@Select("select * from student where sname like concat('%',#{sname},'%')")
List<Student> getListBySname(String sname);//根据学生的名字模糊查询
@Insert("insert into student(sname,sex,age) values(#{sname},#{sex},#{age})")
int addStu(Student stu); //增加功能
@Delete("delete from student where sno=#{sno}")
int deleteStu(Integer sno);//删去功能
@Update("update student set sname=#{sname},age=#{age} where sno=#{sno}")
int updateStu(Student stu);//修改功能
}
映射文件:对应StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sm.dao.StudentMapper">
</mapper>
业务逻辑层接口
public interface StudentService {
Student selectBySno(Integer sno); //单个参数
List<Student> getStulist(); //查询所有学生
List<Student> getListBySname(String sname);//根据学生的名字模糊查询
int addStu(Student stu); //增加功能
int deleteStu(Integer sno);//删去功能
int updateStu(Student stu);//修改功能
}
业务逻辑层实现
//相当于在spring配置文件中添加了 <bean id="stuService" class="com.yn.service.impl.StudentServiceImpl">
@Service("stuService")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper stuMapper;
@Override
public Student selectBySno(Integer sno) {
return stuMapper.selectBySno(sno);
}
@Override
public List<Student> getStulist() {
return stuMapper.getStulist();
}
@Override
public List<Student> getListBySname(String sname) {
return stuMapper.getListBySname(sname);
}
@Transactional
public int addStu(Student stu) {
return stuMapper.addStu(stu);
}
@Transactional
public int deleteStu(Integer sno) {
return stuMapper.deleteStu(sno);
}
@Transactional
public int updateStu(Student stu) {
return stuMapper.updateStu(stu);
}
}
测试
public class TestSpringMyBatis {
ApplicationContext ac=new ClassPathXmlApplicationContext("spring-config.xml");
StudentService stuService=(StudentService)ac.getBean("stuService");
@Test //获得单个学生
public void selectBySno(){
Student stu=stuService.selectBySno(18);
System.out.println(stu.getSname());
}
@Test //获得所有
public void selectAllStu(){
List<Student> slist=stuService.getStulist();
for (Student stu : slist) {
System.out.println(stu.getSname());
}
}
@Test //根据姓名模糊查
public void selectStuBySname(){
List<Student> slist=stuService.getListBySname("小");
for (Student stu : slist) {
System.out.println(stu.getSname());
}
}
@Test //增加学生
public void addStu(){
Student stu=new Student();
stu.setSname("老张");
stu.setSex("男");
stu.setAge(19);
int num=stuService.addStu(stu);
if(num>0){
System.out.println("add success!");
}
}
@Test //删去学生
public void deleteStu(){
int num=stuService.deleteStu(20);
if(num>0){
System.out.println("delete success!");
}
}
@Test //修改学生
public void updateStu(){
Student stu=new Student();
stu.setSname("玫瑰");
stu.setAge(18);
stu.setSno(9);
int num=stuService.updateStu(stu);
if(num>0){
System.out.println("update success!");
}
}
}
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。