前言
很久没有引入mybatis进行开发,一直用mybatis-plus,其中内容忘记了很多,正好在更新脚手架项目,想着把mybatis捡起来研究一番,把功能简单封装,编写自定义的条件构造器等等,加入到脚手架中作为备用的增删改查dao,从而学习一下mybatis里的东西。
正文
创建项目
使用idea新建项目,建立以下模块:
mybatis-curd | mybatis-dynamic-datasource | web-test |
---|---|---|
通用操作模块 | 数据源模块 | web/功能验证模块 |
下文简称:curd | 下文简称:datasource | 下文简称:web |
项目依赖
name | version |
---|---|
spring-boot-starter-parent | 3.1.0 |
mysql-connector-j | 8.3.0 |
aspectjweaver | 1.9.21.1 |
mybatis-spring | 3.0.1 |
spring-context | 6.0.9 |
spring-boot-configuration-processor | 3.1.5 |
log4j-api | 2.20.0 |
spring-test | 6.0.9 |
mybatis | 3.5.11 |
... | ... |
完整依赖见GitHub项目pom文件
根目录的pom文件中作为项目依赖的版本管理,curd模块引入mybatis+spring+springboot自动配置相关依赖 ,datasource模块引入curd模块。最后web模块同时引入以上两者+spring-boot-web+spring-boot-test依赖
项目目录一览
配置mybatis数据源(dataSource模块)
由于项目中后续可能使用动态数据源,所以添加了dataSource模块,目前先使用mysql的DriverManagerDataSource。创建DataSourceConfiguration引入项目中要使用的配置文件中的spring.datasource内容,创建DataSourceConfig用于读取配置文件数据源基础内容,创建DataSourceConfiguration用于自动装配dataSource bean。
java
@Component
@ConfigurationProperties("spring.datasource")
@Data
public class DataSourceConfig {
private String url;
private String username;
private String password;
private String driverClassName;
private String type;
}
读取数据源配置类
less
@Configuration
@EnableConfigurationProperties(DataSourceConfig.class)
@RequiredArgsConstructor
public class DataSourceConfiguration {
private final DataSourceConfig dataSourceConfig;
@Bean("dataSource")
public DataSource setDriverManagerDataSource(){
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setUrl(dataSourceConfig.getUrl());
driverManagerDataSource.setDriverClassName(dataSourceConfig.getDriverClassName());
driverManagerDataSource.setPassword(dataSourceConfig.getPassword());
driverManagerDataSource.setUsername(dataSourceConfig.getUsername());
return driverManagerDataSource;
}
}
dataSource bean配置类
写完配置类后,需要在ressources/META-INF/spring.factories中填上需要springboot自动装配的类的位置。
配置mybatis-sqlSessionFactory(curd模块)
配置sqlSessionFactory的步骤与dataSource类似,先新建读取配置类、sqlSessionFactory配置类和spring.factories,需要额外新建mybatis-config.xml核心配置文件。
java
@Setter
@Getter
@Component
@ConfigurationProperties("nott.mybatis")
public class NottMybatisConfig {
/**
* mybatis 配置文件地址
*/
private String mybatisConfigLocation = "META-INF/spring/mybatis-config.xml";
private String mapperLocation;
// private String mybatisBasePackage;
}
读取配置
java
@Configuration
@EnableConfigurationProperties(NottMybatisConfig.class)
@RequiredArgsConstructor
public class MybatisAutoConfiguration {
private final NottMybatisConfig nottMybatisConfig;
@Bean("sqlSessionFactory")
public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(nottMybatisConfig.getMapperLocation()));
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(nottMybatisConfig.getMybatisConfigLocation()));
return sqlSessionFactoryBean;
}
}
sqlSessionFactory bean配置类(事物管理配置待定)
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="logPrefix" value="nott-mybaits-"/>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
mybatis-config.xml
spring.factories
验证配置(web模块)
yml
logging:
config: classpath:logback.xml
level:
org.nott.mapper: debug
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
nott:
mybatis:
mapper-location: classpath:mapper/**Mapper.xml
项目配置application.yml
编写Application启动类
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="org.nott.web.mapper.UserMapper">
<select id="selectUser" resultType="org.nott.web.entity.User">
select * from user where id = #{id}
</select>
</mapper>
java
public interface UserMapper {
User selectUser(String id);
}
编写测试用的mapper.xml和mapper接口
sql
INSERT INTO `test`.`user` (`id`, `email`, `name`, `password`) VALUES ('410544b2-4001-4271-9855-fec4b6a6442a', 'test@email.com', 'youKnowWho', '$2b$10$xupd3MaYf1fA2wMjaNl6AuTyBE2ifOGd2xbUVpdV1fgqYyBi9XiRy');
插入数据
java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = Application.class)
public class MybatisTestClass {
private ClassPathXmlApplicationContext context;
@Resource
private UserMapper userMapper;
@Test
public void testIssues01(){
String id = "410544b2-4001-4271-9855-fec4b6a6442a";
User user = userMapper.selectUser(id);
System.out.println(user);
}
}
测试类&结果
小结
以上测试结果表明我们的crud和dataSource模块已经自动装配到web模块了,下一步就是编写通用的SQL语句构造器实现SQL编辑的功能。