使用版本与支持
快速上手
安装
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.2</version>
</dependency>
- 直接导入依赖即可
配置
注解配置
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
return factoryBean.getObject();
}
}
datasource在xml进行配置方便属性值的设置
xml文件配置
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
mapper映射的使用
- 需要注意的是:所指定的映射器类必须是一个接口,而不是具体的实现类。在这个示例中,通过注解来指定 SQL 语句,但是也可以使用 MyBatis 映射器的 XML 配置文件。
注解指定sql
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(int id);
}
- 在xml进行配置
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.beyondzy.spring.dao.UserMapper" />
<property name="sqlSessionFactory" ref="sessionFactory" />
</bean>
xml指定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="com.ggs.dao.UserMapper">
<select parameterType="int" id="selectNameById">
select username from users where id = #{id};
</select>
</mapper>
<!--将mapper的xml配置到sessionfactory中-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="mapper/*.xml"></property>
</bean>
SqlSessionFactory中的属性
configLocation
- 它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是 或 元素。任何环境配置(),数据源()和 MyBatis 的事务管理器()都会被忽略。
- 因此可以这个配置文件将关于数据库的内容一起进行配置。
需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。确切地说,任何环境配置(),数据源()和 MyBatis 的事务管理器()都会被忽略。
mapperLocations
- 指定mapper文件的目录