创建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, '[email protected]'),
-> (2, 'Jack', 20, '[email protected]'),
-> (3, 'Tom', 28, '[email protected]'),
-> (4, 'Sandy', 21, '[email protected]'),
-> (5, 'Billie', 24, '[email protected]');
Query OK, 5 rows affected (0.02 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql>
添加Mybatis提供的starter
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
可以看到mybatis-spring-boot-starter的依赖了spring-boot-starter-jdbc、mybatis、mybatis-spring
查看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类,可以看到:
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 {
......省略部分......
}
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;
}
指定mybatis配置文件的路径,和mapper.xml文件的位置
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*
说明:
configuration中的配置,都可以在application.properties中实现,但是在application.properties中指定了mybatis.configuration,就不要mybatis-config.xml文件了,就需要将application.properties的mybatis.config-location配置删除。如下所示:
mybatis.configuration.map-underscore-to-camel-case=true
Mapper接口说明如下:
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文件说明如下:
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);
}
}
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 protected])
......省略部分......
可以不在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);
}
既可以在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 into user(id, name, age, email) values(#{id}, #{name}, #{age}, #{email})
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, "[email protected]");
userService.insertUser(insertUser);
}
}