開發環境:
開發工具:Intellij IDEA 2017.2.3
JDK : 1.8.0_144
spring boot 版本 : 1.5.10.RELEASE
maven : 3.2.3
SpringBoot集成MyBatis加入基礎依賴:
mybatis:
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--通用mapper插件-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.5</version>
</dependency>
MySQL:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
數據庫配置:
application.yml
spring:
datasource:
url: jdbc:mysql://192.168.1.59:3306/test?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
在Mysql數據庫中建立數據表:
CREATE DATABASE mytest;
USE mytest;
CREATE TABLE t_user(
id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
MyBatis
配置文件配置
:
application.yml(
映射文件配置的位置
)
#初始化自定義的接口mapper
mapper:
mappers:
com.test2.mapper.CommonMapper
not-empty: false
identity:
MYSQL
使用Mybatis:
建立映射對象User
/** * User實體映射類
* Created by Administrator on 2017/11/24.
*/
@Table
(name =
"t_user"
)
public class User {
@Id
private Integer id;
private String name;
private String password;
private String phone;
//省略 get 和 set ...
}
實現本身的接口,繼承通用的mapper
package com.test2.mapper;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface CommonMapper<T> extends Mapper<T>,MySqlMapper<T> {
//這裏實現一個本身的接口,繼承通用的mapper,關鍵點就是這個接口不能被掃描到(不加註解就不會被掃描到),
}
建立User映射的操做UserMapper,爲了後續單元測試驗證,實現插入和查詢操做
@Mapper
public interface UserMapper extends CommonMapper<User>{
}
建立單元測試:
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void insert(){
User user = new User();
user.setName("aaa");
user.setPassword("222222");
user.setPhone("123456");
userMapper.insert(user);
}
}
通用mapper版:
1.首先須要在pom.xml中引入
通用mapper插件包;
2.在建立實體類
時,須要指明表名和主鍵id
3.
實現本身的通用接口,繼承通用的mapper
4.建立的mapper接口,只須要繼承自定義的通用接口就可使用默認的方法
注意:配置版、通用mapper版、配置文件版,這三版能夠混合使用,