准备
1、使用 Maven 构建 SpringBoot 项目,引入如下场景启动器:
2、引入 Druid 依赖,配置 Druid 数据源,初始化测试表:
# application.yml
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.202.135:3306/springboot_mybatis
driver-class-name: com.mysql.jdbc.Driver
# Durid 独有的属性
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 1 from DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的 filter ,去掉后监控界面无法统计,wall 用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
schema:
- classpath:sql/user-schema.sql
data:
- classpath:sql/user-data.sql
-- sql/user-schema.sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) DEFAULT NULL,
`gender` int(11) DEFAULT NULL COMMENT '0:女 1:男',
`birthday` date DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
-- sql/user-data.sql
INSERT INTO `user` VALUES ('1', '张三', '1', '1997-02-23', '北京');
INSERT INTO `user` VALUES ('2', '李四', '0', '1998-02-03', '武汉');
INSERT INTO `user` VALUES ('3', '王五', '1', '1996-06-04', '上海');
3、创建与测试表对应的 JavaBean:
// com.springboot.data_mybatis.bean.User
import java.util.Date;
public class User {
private Integer id;
private String name;
private Integer gender;
private Date birthday;
private String address;
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;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
注解方式整合
编写 mapper 类,并在 mapper 类中通过注解绑定 sql:
// com.springboot.data_mybatis.mapper.UserMappper
import com.springboot.data_mybatis.bean.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMappper {
@Select("select * from user")
public List<User> getAll();
@Select("select * from user where id=#{id}")
public User getById(Integer id);
@Delete("delete from user where id=#{id}")
public Integer deleteById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into user(name,gender,birthday,address) values(#{name},#{gender},#{birthday},#{address})")
public Integer add(User user);
@Update("update user set name=#{name},gender=#{gender},birthday=#{birthday},address=#{address} where id=#{id}")
public Integer update(User user);
}
测试:
import com.springboot.data_mybatis.bean.User;
import com.springboot.data_mybatis.mapper.UserMappper;
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 javax.sql.DataSource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@SuppressWarnings("all")
public class DataMybatisApplicationTests {
@Autowired
private DataSource dataSource;
@Test
public void test() {
System.out.println(dataSource.getClass());
}
@Autowired
private UserMappper userMappper;
@Test
public void testGetAll(){
List<User> all = userMappper.getAll();
System.out.println(all);
/*
[User{id=1, name='张三'}, User{id=2, name='李四'}, User{id=3, name='王五'}]
*/
}
@Test
public void testGetById(){
User user = userMappper.getById(1);
System.out.println(user);
/*
User{id=1, name='张三'}
*/
}
@Test
public void testAdd() throws ParseException {
User user = new User();
user.setName("赵六");
user.setGender(1);
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1998-2-2"));
user.setAddress("南京");
Integer count = userMappper.add(user);
System.out.println(count);
/*
*/
}
@Test
public void testUpdate(){
User user = userMappper.getById(4);
user.setGender(0);
Integer count = userMappper.update(user);
System.out.println(count);
/*
*/
}
@Test
public void testDelete(){
Integer count = userMappper.deleteById(4);
System.out.println(count);
/*
*/
}
}
补充
示例中是在 mapper 类上添加了 @Mapper 注解用来标识所标注的类是一个 Mapper 类,还可以通过 @MapperScan
注解配置 mapper 类的包扫描:
@MapperScan("com.springboot.data_mybatis.mapper")
可以看到上述注解方式没有 MyBatis 的核心配置文件,如果需要自定制 MyBatis 的部分配置,SpringBoot 给我们提供了 MyBatis 配置自定制类,我们只需要设置好该类实例相关属性将其放入 IoC 容器即可生效:
// com.springboot.data_mybatis.config.MyBatisConfig
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
// 启用驼峰命名,表字段 user_name 可映射到 userName 属性
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
XML 方式配置
添加 MyBatis 核心配置文件:
<!-- 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>
<!--启用驼峰命名,表字段 user_name 可映射到 userName -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
在 SpringBoot 配置文件中指定 MyBatis 核心配置文件和映射文件位置:
# application.yml
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.202.135:3306/springboot_mybatis
driver-class-name: com.mysql.jdbc.Driver
# Durid 独有的属性
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 1 from DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的 filter ,去掉后监控界面无法统计,wall 用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
# schema:
# - classpath:sql/user-schema.sql
# data:
# - classpath:sql/user-data.sql
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
编写 mapper 类:
// com.springboot.data_mybatis.mapper.UserMappper
import com.springboot.data_mybatis.bean.User;
import java.util.List;
public interface UserMappper {
public List<User> getAll();
public User getById(Integer id);
public Integer deleteById(Integer id);
public Integer add(User user);
public Integer update(User user);
}
编写映射文件:
<!-- mybatis/mapper/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.springboot.data_mybatis.mapper.UserMappper">
<select id="getAll" resultType="com.springboot.data_mybatis.bean.User">
select * from user
</select>
<select id="getById" parameterType="int" resultType="com.springboot.data_mybatis.bean.User">
select * from user where id=#{id}
</select>
<delete id="deleteById" parameterType="int">
delete from user where id=#{id}
</delete>
<insert id="add" parameterType="com.springboot.data_mybatis.bean.User" useGeneratedKeys="true" keyProperty="id">
insert into user(name,gender,birthday,address) values(#{name},#{gender},#{birthday},#{address})
</insert>
<update id="update" parameterType="com.springboot.data_mybatis.bean.User">
update user set name=#{name},gender=#{gender},birthday=#{birthday},address=#{address} where id=#{id}
</update>
</mapper>
使用注解配置 mapper 类所在的包扫描:
// com.springboot.data_mybatis.DataMybatisApplication
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.springboot.data_mybatis.mapper")
public class DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(DataMybatisApplication.class, args);
}
}
测试:
import com.springboot.data_mybatis.bean.User;
import com.springboot.data_mybatis.mapper.UserMappper;
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 javax.sql.DataSource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
@SuppressWarnings("all")
public class DataMybatisApplicationTests {
@Autowired
private DataSource dataSource;
@Test
public void test() {
System.out.println(dataSource.getClass());
}
@Autowired
private UserMappper userMappper;
@Test
public void testGetAll(){
List<User> all = userMappper.getAll();
System.out.println(all);
/*
[User{id=1, name='张三'}, User{id=2, name='李四'}, User{id=3, name='王五'}]
*/
}
@Test
public void testGetById(){
User user = userMappper.getById(1);
System.out.println(user);
/*
User{id=1, name='张三'}
*/
}
@Test
public void testAdd() throws ParseException {
User user = new User();
user.setName("赵六");
user.setGender(1);
user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1998-2-2"));
user.setAddress("南京");
Integer count = userMappper.add(user);
System.out.println(count);
/*
*/
}
@Test
public void testUpdate(){
User user = userMappper.getById(5);
user.setGender(0);
Integer count = userMappper.update(user);
System.out.println(count);
/*
*/
}
@Test
public void testDelete(){
Integer count = userMappper.deleteById(5);
System.out.println(count);
/*
*/
}
}
评论区