Spring整合Mybatis核心总结

简单回顾:在普通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不是必需的,可以将这些信息的配置转移到下面dataSourceSqlSessionFactoryBeanBean配置中进行。

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&amp;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));
        
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值