在前面的博客中我已经介绍了MyBatis和Spring比较详细的内容,在实际的使用中各个框架经常是联合起来一起使用,以达到最好的效果,曾经最流行的或者说现在还有大部分公司的java项目,都是用Sping+MyBatis+SpringMVC开发完成。
今天我们先实战MyBatis和Spring的整合,使用 MyBatis-Spring 使得业务层和模型层得到了更好的分离,与此同时,在 Spring 环境中使用 MyBatis 也更加简单,节省了不少代码,甚至可以不用 SqlSessionFactory、 SqlSession 等对象,因为 MyBatis-Spring 为我们封装了它们。接下来就通过实际操作来理解MyBatis与Spring整合的过程和注意点:
创建项目可以用Maven也可以是最普通的方式创建,这次的MS整合我们采用最普通的项目创建方式,接下来的SSM框架整合会用到Maven项目;
https://blog.csdn.net/qq_41973594/article/details/95037638
在src路径下创建com.sdxb.ly包,在包下创建dao、mapper、pojo、test、config五个包,创建db.properties和log4j.properties,导入所需的jar包(Spring、Mybatis、mybatis-spring、mysql-connector-java),在文章的最后附上了github连接,想要jar包的可以直接去下,最终的项目结构如下图:
第二步:编写db.properties和log4j.properties
db.properties中包含数据库连接所需的一系列配置,log4j.properties用来记录日志,log4j详细介绍也可看往期博客:
//按照自己的数据库修改
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mybatistest?characterEncoding=UTF-8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
log4j.properties
# Global logging configuration
# 在开发环境下日志级别要设置成 DEBUG ,生产环境设为 INFO 或 ERROR
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
第三步:编写Spring配置文件
Spring的配置文件为applicationConfig.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载db.properties配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.jdbcUrl}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载Mybatis的配置文件-->
<property name="configLocation" value="classpath:com/sdxb/ly/config/mybatis/SqlMapConfig.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
第四步:编写Mybatis的配置文件
Mybatis的配置文件为mybatisConfig.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>
<!-- 创建别名-->
<typeAliases>
<package name="com.sdxb.ly"/>
</typeAliases>
<!-- 编写映射 -->
<mappers>
<mapper resource="com/sdxb/ly/config/sqlmap/Studentmapper.xml"/>
<package name="com.sdxb.ly"/>
</mappers>
</configuration>
第五步:编写Mapper和实体类
本项目采用的数据库是包含学生id,学生name,班级号classid的学生数据库表,创建实体类:
public class Student implements Serializable {
private int id;
private String name;
private int classid;
//getter and setter
}
编写Mapper文件,先写一个查询学生姓名的sql语句:
<?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="test">
<select id="selectstudent" resultType="Student">
select * from student
</select>
</mapper>
第六步:编写数据库交互层(DAO)
对于dao层和之后会接触到的service层都采用接口+实现类的形式,编写StudentDao接口和StudentDaoImpl实现类
public interface StudentDao {
List<Student> selectstudent() throws Exception;
}
StudentDaoImpl
package com.sdxb.ly.dao;
import com.sdxb.ly.pojo.Student;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class StudentDaoImpl extends SqlSessionDaoSupport implements StudentDao{
@Override
public List<Student> selectstudent() throws Exception {
SqlSession session=this.getSqlSession();
List<Student> student=session.selectList("selectstudent");
return student;
}
}
在编写StudentDaoImpl时,继承了SqlSessionDaoSupport类,SqlSessionDaoSupport是Spring-Mybatis整合jar包中提供的一个类,该类包含了SqlSessionFactory类,提供get和set方法,更加方便Spring从外部注入SqlSessionFactory对象。
因此我们需要在applicationContext.xml中增加StudentDao的bean配置,将定义的SqlSessionFactory注入
<bean id="studentDao" class="com.sdxb.ly.dao.StudentDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
第七步:最终测试
public class TestSpringMybatis {
@Test
public void test() throws Exception {
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("classpath:com/sdxb/ly/config/spring/applicationContext.xml");
StudentDao studentDao= (StudentDao) applicationContext.getBean("studentDao");
List<Student> students=studentDao.selectstudent();
for (Student student:students){
System.out.println(student.getName());
}
}
}
-------------------------------------------------------------------------------------------------------------------------------------
使用注解加动态代理的方式可以让代码显得更加简洁干净,接下来就通过这个方式修改项目:
package com.sdxb.ly.mapper;
import com.sdxb.ly.pojo.Student;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("studentMapper")
public interface StudentMapper{
@Select("select * from student")
List<Student> selectStudent() throws Exception;
}
通过注解的方式实现查询学生的功能,接下来在applicationContext.xml文件中增加mapper扫描器:
<!-- Mapper 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描 mapper 包下的组件 -->
<property name="basePackage" value="com.sdxb.ly.mapper"/>
</bean>
配置完成后扫描器会扫描mapper包下的类,自动创建代理对象并且在 Spring 容器中注入,所以StudentMapper接口即使不使用@Component声明bean对象也一样可以由默认的代理对象实现同样的功能,接下来进行测试:
@Test
public void test2() throws Exception {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:com/sdxb/ly/config/spring/applicationContext.xml");
StudentMapper studentMapper= (StudentMapper) applicationContext.getBean("Student");
List<Student> students=studentMapper.selectStudent();
for (Student student:students){
System.out.println(student.getName());
}
}