SpringBoot2.0学习(四)-MyBatis
MyBatis是一款优秀的持久层构架,它支持定制化SQL语句、存储过程以及高级映射,可以通过简单的XML或注解配置和映射原生信息,将POJOs映射成数据库中的记录,从而方便进行增删改查的操作(官网)。本文会分别介绍通过XML、自动生成、注解三种传统使用MyBatis的方式以及在SpringBoot中使用MyBatis。
1. XML配置方式使用MyBatis
1.1 引入依赖(jdbc,mysql,mybatis)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.2 配置数据库连接信息
resources:mybatis/mybatis.properties
jdbc.driver-class=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/test
1.3 配置Mybatis
resources:mybatis/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>
<properties resource="mybatis/mybatis.properties" />
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver-class}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/mappers/UserMapper.xml"/>
</mappers>
</configuration>
1.4 配置映射信息
resources:mybatis/mappers/UserMapper.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.hebaohua.springbootmybatis.mappers.UserMapper">
<select id="selectUser" resultType="com.hebaohua.springbootmybatis.entity.User">
select * from user where id = #{id}
</select>
</mapper>
1.5运行测试
public class XmlConfigDemo {
public static void main(String[] args) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("classpath:/mybatis/mybatis-config.xml");
InputStream inputStream = resource.getInputStream();
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
User user = session.selectOne("com.hebaohua.springbootmybatis.mappers.UserMapper.selectUser", 4);
System.out.println(user);
} finally {
session.close();
}
}
}
运行效果:
2. 使用MyBatis配置生成器
此处只讲解在idea中使用maven连接Mysql的配置方式, 其它可以查看网址.
2.1 首先添加Maven插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</plugin>
注意: 不要忘了下面的mysql驱动依赖
2.2 编写生成配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="TestTables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="123456">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- Java 模型对象生成器 -->
<javaModelGenerator targetPackage="com.hebaohua.springbootmybatisgenerator.entity"
targetProject="${user.dir}/src/main/java"/>
<!-- SQL Mapper XML 生成器 -->
<sqlMapGenerator targetPackage="mybatis.mappers" targetProject="${user.dir}/src/main/resources"/>
<!-- SQL Mapper Java 接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.hebaohua.springbootmybatisgenerator.mappers"
targetProject="${user.dir}/src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="user" domainObjectName="User" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="MySQL" identity="true" />
<columnOverride column="name"/>
<columnOverride column="age"/>
</table>
</context>
</generatorConfiguration>
注意命名为generatorConfig.xml,并且直接放在resources下面
2.3 执行生成命令
在项目根目录打开命令窗口并执行mvn mybatis-generator:generate
下图中的四个文件,然后其添加如XML方式中的配置信息。
2.4 运行测试
上一步中产生的文件提供了关于数据库user表中丰富的增删改查接口,使我们在使用起来非常的方便。
public class Demo {
public static void main(String[] args) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("classpath:/mybatis/mybatis-config.xml");
InputStream inputStream = resource.getInputStream();
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> users = userMapper.selectByExample(null);
System.out.println(users);
} finally {
session.close();
}
}
}
运行效果:
3. 使用注解
注解的方式总是能减少繁琐的配置文件。
3.1 编写注解Mapper
@Mapper
public interface UserMapper {
@Results(value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
@Select("SELECT id,name,age FROM user WHERE id = #{id}")
User selectUser(int id);
}
3.2 运行测试
同样需要引入全局配置文件,并注意要增加以下内容:
<mappers>
<mapper class="com.hebaohua.springbootmybatisannotation.mappers.UserMapper"/>
</mappers>
测试代码:
public class Demo {
public static void main(String[] args) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("classpath:/mybatis/mybatis-config.xml");
InputStream inputStream = resource.getInputStream();
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper userMapper = session.getMapper(UserMapper.class);
User user= userMapper.selectUser(4);
System.out.println(user);
} finally {
session.close();
}
}
}
运行效果:
4.SpringBoot中使用MyBatis
通过查看 MybatisAutoConfiguration
以及MybatisProperties
源码可知,在SpringBoot的配置文件中配置好datasource以及以“mybatis”开头的相关配置就会自动装配SqlSessionFactory
,SqlSessionTemplate
对象,因此在Contorller中就可以直接使用。
@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
/**
* Location of MyBatis xml config file.
*/
private String configLocation;
SpringBoot配置文件:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/test
mybatis.config-location=classpath:/mybatis/mybatis-config.xml
Controller类:
@RestController
public class MyBatisController {
@Autowired
private SqlSessionTemplate sqlSessionTemplate;
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id){
User user = sqlSessionTemplate.selectOne("com.hebaohua.springbootmybatisannotation.mappers.UserMapper.selectUser",id);
return user;
}
}
运行效果: