目录
1. 创建Mysql表和添加测试数据
创建Mysql表,如下所示:
mysql> create table user (
-> id bigint(20) auto_increment not null comment '主键ID',
-> name varchar(30) null default null comment '姓名',
-> age int(11) null default null comment '年龄',
-> email varchar(50) null default null comment '邮箱',
-> primary key (id)
-> );
Query OK, 0 rows affected, 2 warnings (0.01 sec)
mysql>
添加测试数据,如下所示:
mysql> insert into user (id, name, age, email) values
-> (1, 'Jone', 18, 'test1@mybatis.com'),
-> (2, 'Jack', 20, 'test2@mybatis.com'),
-> (3, 'Tom', 28, 'test3@mybatis.com'),
-> (4, 'Sandy', 21, 'test4@mybatis.com'),
-> (5, 'Billie', 24, 'test5@mybatis.com');
Query OK, 5 rows affected (0.02 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql>
2. 添加pom.xml依赖
添加Mybatis提供的starter
<!-- 支持spring 2.6.3 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
可以看到mybatis-spring-boot-starter的依赖了spring-boot-starter-jdbc、mybatis、mybatis-spring
3. 自动配置分析
查看mybatis-spring-boot-autoconfigure-2.2.2.jar的META-INF\spring.factories,可以看到给我们自动配置了MybatisLanguageDriverAutoConfiguration和MybatisAutoConfiguration
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
现在我们重点来看MybatisAutoConfiguration类,可以看到:
- 当IOC容器中只有一个DataSource才生效
- 绑定了MybatisProperties配置类
- 向IOC容器添加了SqlSessionFactory,并且SqlSessionFactory设置了dataSource
- 向IOC容器添加了SqlSessionTemplate,里面就有SqlSession,就可以对数据库进行crud操作
- 向IOC容器添加了AutoConfiguredMapperScannerRegistrar,会扫描配置文件指定的位置,将标注了@Mapper的接口添加到IOC容器,这些接口是操作Mybatis的接口
package org.mybatis.spring.boot.autoconfigure;
......省略部分......
@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisAutoConfiguration implements InitializingBean {
......省略部分......
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
......省略部分......
}
......省略部分......
@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
ExecutorType executorType = this.properties.getExecutorType();
return executorType != null ? new SqlSessionTemplate(sqlSessionFactory, executorType) : new SqlSessionTemplate(sqlSessionFactory);
}
......省略部分......
@Configuration
@Import({AutoConfiguredMapperScannerRegistrar.class})
@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {
public MapperScannerRegistrarNotFoundConfiguration() {
}
public void afterPropertiesSet() {
MybatisAutoConfiguration.logger.debug("Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
}
}
public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, EnvironmentAware, ImportBeanDefinitionRegistrar {
private BeanFactory beanFactory;
private Environment environment;
public AutoConfiguredMapperScannerRegistrar() {
}
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (!AutoConfigurationPackages.has(this.beanFactory)) {
MybatisAutoConfiguration.logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
} else {
MybatisAutoConfiguration.logger.debug("Searching for mappers annotated with @Mapper");
......省略部分......
}
......省略部分......
}
......省略部分......
}
......省略部分......
}
查看MybatisProperties配置类,Mybatis的配置由mybatis开头的配置进行配置的
......省略部分......
@ConfigurationProperties(
prefix = "mybatis"
)
public class MybatisProperties {
......省略部分......
}
4. 代码实现
4.1 User类实现
- 类名不用和表名对应
- 字段需要一一对应
package com.hh.springboottest.myController;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
4.2 application.properties配置
指定mybatis配置文件的路径,和mapper.xml文件的位置
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*
4.3 mybatis-config.xml配置文件
说明:
- 设置mapUnderscoreToCamelCase为true,意思是让数据库表的字段user-name,和类的属性是UserName对应起来
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 让数据库表的字段user-name,和类的属性是UserName对应起来 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
configuration中的配置,都可以在application.properties中实现,但是在application.properties中指定了mybatis.configuration,就不要mybatis-config.xml文件了,就需要将application.properties的mybatis.config-location配置删除。如下所示:
mybatis.configuration.map-underscore-to-camel-case=true
4.4 Mapper接口和Mapper.xml实现
Mapper接口说明如下:
- Mapper接口需要用@Mapper注解标识。也可以在SpringBoot的启动类中,用注解@MapperScan(“com.hh.springboottest.mapper”)声明Mapper接口的扫描路径
- 同时声明操作数据的方法getUser,等会在Mapper.xml中实现
package com.hh.springboottest.mapper;
import com.hh.springboottest.myController.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserMapper {
public User getUser(@Param("id") Long id);
}
Mapper.xml文件说明如下:
- namespace指定对应的Mapper接口
- 查询数据就用select标签,id和Mapper接口的方法名对应,resultType和Mapper接口的方法的返回值对应
- select查询语句的常量值从Mapper接口的方法参数获取
- 也可以返回map。则resultType=“map”,返回的对象是Map<String, Object>,key是字段名,value是字段值
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hh.springboottest.mapper.UserMapper">
<!-- public User getUser(Long id); -->
<select id="getUser" resultType="com.hh.springboottest.myController.User">
select * from user where id = #{id}
</select>
</mapper>
4.5 Service实现
UserService接口实现如下:
package com.hh.springboottest.service;
import com.hh.springboottest.myController.User;
public interface UserService {
public User getUser(Long id);
}
UserServiceImpl实现类如下:
package com.hh.springboottest.service.impl;
import com.hh.springboottest.mapper.UserMapper;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
public User getUser(Long id) {
return userMapper.getUser(id);
}
}
4.6 UserMapper测试
package com.hh.springboottest;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@Slf4j
@SpringBootTest
public class MyApplicationTest {
@Autowired
UserService userService;
@Test
public void queryDataTest() {
User user = userService.getUser(1L);
log.info("获取到的用户信息: {}", user);
}
}
运行程序,结果如下:
......省略部分......
2022-11-21 06:56:51.768 INFO 7824 --- [ main] com.hh.springboottest.MyApplicationTest : 获取到的用户信息: User(id=1, name=Jone, age=18, email=test1@mybatis.com)
......省略部分......
5. 注解版开发
可以不在application.properties指定mybatis.mapper-locations配置参数,不用Mapper.xml文件,直接使用注解进行开发。如下所示:
package com.hh.springboottest.mapper;
import com.hh.springboottest.myController.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
public User getUser(Long id);
}
6. 混合版(配置 + 注解)
既可以在Mapper.xml中使用配置文件的方式,也可以在Mapper接口使用注解
UserMapper接口实现如下:
package com.hh.springboottest.mapper;
import com.hh.springboottest.myController.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
public User getUser(Long id);
public void insertUser(User user);
}
UserMapper.xml文件如下。说明:
- 向数据库插入数据使用insert标签
- 可以直接获取User类的属性值
- 如果没有传入User.id, useGeneratedKeys会将数据库生成的自增id返回,重新赋值给User
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hh.springboottest.mapper.UserMapper">
<!-- public User getUser(Long id); -->
<select id="getUser-noUse" resultType="com.hh.springboottest.myController.User">
select * from user where id = #{id}
</select>
<!-- public void insertUser(User user); -->
<!-- 如果没有传入User.id, useGeneratedKeys会将数据库生成的自增id返回,重新赋值给User -->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into user(id, name, age, email) values(#{id}, #{name}, #{age}, #{email})
</insert>
</mapper>
insertUser如果使用注解开发,如下所示:
@Insert("insert into user(id, name, age, email) values(#{id}, #{name}, #{age}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
public void insertUser(User user);
UserService接口如下:
package com.hh.springboottest.service;
import com.hh.springboottest.myController.User;
public interface UserService {
public User getUser(Long id);
public void insertUser(User user);
}
UserServiceImpl实现类如下:
package com.hh.springboottest.service.impl;
import com.hh.springboottest.mapper.UserMapper;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
public User getUser(Long id) {
return userMapper.getUser(id);
}
@Override
public void insertUser(User user) {
userMapper.insertUser(user);
}
}
Mapper测试如下:
package com.hh.springboottest;
import com.hh.springboottest.myController.User;
import com.hh.springboottest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
@Slf4j
@SpringBootTest
public class MyApplicationTest {
@Autowired
UserService userService;
@Test
public void queryDataTest() {
User user = userService.getUser(1L);
log.info("获取到的用户信息: {}", user);
User insertUser = new User(6L, "Lily", 24, "test6@mybatis.com");
userService.insertUser(insertUser);
}
}