SpringMVC 集成 MyBatis
吐嘈一下 Mapper 在 IDEA 里注入识别不了就加 @Repository 的人,咋不去加个 @Controller 呢?自己做啥都不知道能跑就行的人,活该做一辈子码农。
前言
因为 MyBatis 基本只有国人在用,IDEA 对于 MyBatis 的支持并不好,需要安装 MyBatis 相关插件才能正确识别 Mapper 注入,我这里装的是 MyBatisCodeHelperPro。
集成
依赖
org.mybatis:mybatis 与 org.mybatis:mybatis-spring,前者提供 MyBatis 核心功能,后者提供 Spring 集成相关功能。根应用上下文
...
@EnableTransactionManagement(
mode = AdviceMode.PROXY,
proxyTargetClass = true
)
@MapperScan({"com.seliote.mt.mapper"})
...
@Bean
public TransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return factoryBean.getObject();
}
...- 实体类就 POJO 即可
...
@Data
public class SysIndexEntity {
private String id;
private Integer type;
private Integer status;
private String msg;
private LocalDateTime createDate;
private LocalDateTime lastModifiedDate;
....
}- 定义 Mapper 与 xml,文件名随意
public interface SysIndexMapper {
SysIndexEntity findOne();
Integer insert();
}<?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.seliote.mt.mapper.SysIndexMapper">
<select id="findOne" resultType="com.seliote.mt.entity.SysIndexEntity">
SELECT *
FROM sys_index
LIMIT 0, 1
</select>
<insert id="insert">
INSERT INTO sys_index
VALUES (UUID(), "33", "23", "TEST3", "2020-05-03 23:58:53", "2020-05-03 23:58:53")
</insert>
</mapper> 相关推荐
dongxurr 2020-08-08
Dullonjiang 2020-07-30
liqiancao 2020-07-26
helloxusir 2020-07-08
mituan 2020-06-14
xiuyangsong 2020-11-16
Nishinoshou 2020-11-09
jimgreatly 2020-09-01
dongxurr 2020-08-18
Dullonjiang 2020-08-15
Dullonjiang 2020-08-11
Dullonjiang 2020-08-09
yunzhonmghe 2020-08-07
jimgreatly 2020-08-03
jimgreatly 2020-07-27
xiuyangsong 2020-07-26
dongxurr 2020-07-26
mcvsyy 2020-07-26