简单回顾:在普通Mybatis项目中,执行查询操作的几个步骤:
-
在
SqlSessionFactoryBuilder
中载入mybatis-config.xml
配置取得SqlSessionFactory
对象。 -
从
SqlSessionFactory
取得SqlSession
对象。 -
调用
SqlSession
相应的查询方法完成查询。String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); try (SqlSession session = sqlSessionFactory.openSession()) { User user = (User) session.selectOne("com.codeqis.joyful.dao.UserMapper.getUser", 101); }
Mybatis与Spring整合的实质是将Mybatis的核心组件SqlSessionFactory等等交由容器管理。同上面示例不同的是,无需在业务代码中显式创建SqlSessionFactory
与操作SqlSession
。容器在启动时读取配置完成对工厂的构建与每个mapper代理对象的创建。
pom.xml导入依赖
<!--mybatis核心-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--还需引入mybatis与spring整合插件-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
创建Mapper接口
/**
* 创建UserMapper接口
*/
public interface UserMapper {
User getUser(String userId);
}
mapper方案1:使用注解指定 SQL 语句
public interface UserMapper {
@Select("SELECT * FROM tb_user WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}
mapper方案2:使用 MyBatis 映射器的 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.codeqis.joyful.dao.UserMapper">
<select id="getUser" resultType="com.codeqis.joyful.model.User" >
SELECT * FROM tb_user WHERE id = #{userId}
</select>
</mapper>
(可选)Mybatis核心配置(mybatis-config.xml)
在非整合的单体Mybatis应用中,通常在mybatis-config.xml
配置数据库连接信息以及mapper映射器相关的一些设置:
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
而在与spring的整合后,mybatis-config.xml
不是必需的,可以将这些信息的配置转移到下面dataSource
和SqlSessionFactoryBean
的Bean
配置中进行。
applicationContext.xml的配置
构建SqlSessionFactory
在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean
来创建 SqlSessionFactory
。
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--若没有mybatis-config.xml可省略该配置项-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--开启自动配置别名-->
<!--若在mybatis-config.xml中有配置此项,该项可省略-->
<property name="typeAliasesPackage" value="com.codeqis.joyful.model"/>
<!--若采用mapper开发方案2,在此配置mapper.xml所在路径,也可在mybatis-config.xml中配置-->
<!--若在mybatis-config.xml中有配置此项,该项可省略-->
<property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" />
</bean>
配置连接池(dataSource)
SqlSessionFactory
需要配置一个dataSource
,可以是任意的DataSource
,这里以c3p0
配置为例:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost/mybatis-spring?useSSL=false&serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="12345678"/>
</bean>
加入MapperFactoryBean
MapperFactoryBean
的作用是将mapper接口的映射器加入到Spring容器中,映射器将负责sqlSessionFactory
的创建和关闭,值得注意的是,这里配置的映射器类均为一个接口,而不是实现类。
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.codeqis.joyful.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
MapperScannerConfigurer包扫描(推荐)
配置MapperScannerConfigurer
使用包扫描创建映射器,指定包下面所有Mapper接口统一创建代理对象,避免为每个mapper接口逐个配置MapperFactoryBean
的繁琐编码。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.codeqis.joyful.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
测试验证
public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User findByUserId(String userId) {
return this.userMapper.getUser(userId);
}
}
public class RunTest {
public static void main() {
// 加载容器
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 获取UserService实例
UserService UserService = context.getBean("userService", UserServiceImpl.class);
// 测试查询
System.out.println(UserService.findByUserId(1));
}
}