一.公共部分
1.创建SpringBoot项目,加入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.peng.demo</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatis</name>
<description>springboot-mybatis</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
注:这里使用阿里巴巴的druid数据库连接池,也可以不使用。
2.创建数据库就数据表
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `tb_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
注:简单创建springboot数据库,在其中创建tb_user数据表
3.创建实体
public class TbUser {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "TbUser [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
public class TbAddress {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TbAddress [id=" + id + ", name=" + name + "]";
}
}
4.配置数据库
在application.properties文件中加入
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
5.配置数据源(不使用druid数据源的可以跳过此步)
在application.properties文件中指定使用的数据源,及配置数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSou
spring.datasource.maxActive=20
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
注:这里配置druid数据源,指定将properties文件中以spring.datasource开头的配置映射到DruidDataSource的属性中
二.通过注解方式配置MyBatis
1.书写Mapper接口
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.peng.demo.pojo.TbUser;
@Mapper
public interface TbUserMapper {
@Select("select * from tb_user where id=#{id}")
TbUser findBuyId(Integer id);
}
注:在类的头上加上@Mapper注解。
2.测试
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.peng.demo.mapper.TbUserMapper;
import com.peng.demo.pojo.TbUser;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {
@Autowired
private TbUserMapper tbUserMapper;
@Test
public void contextLoads() {
TbUser tbUser = tbUserMapper.findBuyId(1);
System.out.println(tbUser);
}
}
测试结果
问题一:如果项目中存在大量mapper接口,每个mapper接口上都加@Mapper注解会很麻烦,SpringBoot提供在主类上加上@MapperScan("com.peng.demo.mapper")的扫描包形式配置mapper,现在去掉TbUserMapper上的注解,测试依旧成功。
问题二:如果将tbUser中的字段username改为userName,tb_user表中的字段username改为user_name查询会出现啥问题呢?
会看到,userName为null,SpringBoot整合MyBatis默认无法识别驼峰命名法,那么如何实现驼峰命名法呢?
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
//开启驼峰命名法
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
配置MyBatis,开启驼峰命名法,测试就成功啦。
三:通过XML文件配置MyBatis
1.创建mapper接口
import com.peng.demo.pojo.TbAddress;
public interface TbAddressMapper {
int insert(TbAddress tbAddress);
}
2.在resource文件夹下创建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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
注:其中mapUnderscoreToCamelCase表示开启驼峰命名法
3.在MyBatis文件夹下创建mapper文件夹,在其下创建TbAddressMapper.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.peng.demo.mapper.TbAddressMapper">
<insert id="insert">
INSERT INTO tb_address(name) VALUES (#{name})
</insert>
</mapper>
4.在application.properties文件中配置MyBatis配置文件地址
mybatis.config-location=classpath:MyBatis/mybatis-config.xml
mybatis.mapper-locations=classpath:MyBatis/mapper/*.xml
5.测试
@Autowired
private TbAddressMapper tbAddressMapper;
@Test
public void test2() {
TbAddress tbAddress = new TbAddress();
tbAddress.setName("杭州");
int insert = tbAddressMapper.insert(tbAddress);
System.out.println(insert);
}
添加成功。
至此,SpringBoot简单整合MyBatis就已经完了,技术一般,如有错误,请留言更正。