MyBatis是一款優(yōu)秀的持久層構(gòu)架亮蒋,它支持定制化SQL語句绪氛、存儲過程以及高級映射揍鸟,可以通過簡單的XML或注解配置和映射原生信息楞黄,將POJOs映射成數(shù)據(jù)庫中的記錄池凄,從而方便進(jìn)行增刪改查的操作(官網(wǎng))。本文會分別介紹通過XML鬼廓、自動生成肿仑、注解三種傳統(tǒng)使用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 配置數(shù)據(jù)庫連接信息
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運(yùn)行測試
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();
}
}
}
運(yùn)行效果:
2. 使用MyBatis配置生成器
此處只講解在idea中使用maven連接Mysql的配置方式, 其它可以查看網(wǎng)址.
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驅(qū)動依賴
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 執(zhí)行生成命令
在項(xiàng)目根目錄打開命令窗口并執(zhí)行mvn mybatis-generator:generate
下圖中的四個文件尤慰,然后其添加如XML方式中的配置信息。
2.4 運(yùn)行測試
上一步中產(chǎn)生的文件提供了關(guān)于數(shù)據(jù)庫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();
}
}
}
運(yùn)行效果:
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 運(yùn)行測試
同樣需要引入全局配置文件匪煌,并注意要增加以下內(nèi)容:
<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();
}
}
}
運(yùn)行效果:
4.SpringBoot中使用MyBatis
通過查看 MybatisAutoConfiguration
以及MybatisProperties
源碼可知责蝠,在SpringBoot的配置文件中配置好datasource以及以“mybatis”開頭的相關(guān)配置就會自動裝配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;
}
}
運(yùn)行效果: