Mapper重复扫描导致@Transactional失效

最近项目中遇到一个问题,一直报“Closing non transactional SqlSession ”具体报错信息如下:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6e0a1219] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1060164214 wrapping com.mysql.cj.jdbc.ConnectionImpl@694234d5] will not be managed by Spring
==>  Preparing: select user_id, user_name, staff_code, account, password, sex, email, phone, photo, state, pinyin, pinyin_short, last_login_time, last_change_pwd_time, org_id,source_user_id,we_chat,qq,identity_number,data_source,`type`, create_time, create_by, last_update_time, last_update_by,dis_code,shop_code from user where user_id = ? 
==> Parameters: f5133142-c6c9-480e-9331-42c6c9c80e3b(String)
<==    Columns: user_id, user_name, staff_code, account, password, sex, email, phone, photo, state, pinyin, pinyin_short, last_login_time, last_change_pwd_time, org_id, source_user_id, we_chat, qq, identity_number, data_source, type, create_time, create_by, last_update_time, last_update_by, dis_code, shop_code
<==        Row: f5133142-c6c9-480e-9331-42c6c9c80e3b, xxx, cs002, zhongzijianzzj, $2a$10$3nmymr07Oz9P9C5v.kCgUOL/ZGHGj9mCRL9EqJacb1nxtHVRA2t4y, 1, *&*(, *(&*&, null, 1, zhongzijian1, zzj1, null, 2019-07-04 11:34:58, 561fc94e-adbc-4b9b-9fc9-4eadbc2b9b0f, null, null, null, null, null, null, 2019-07-04 10:47:32, zhongzijian, 2019-07-11 08:17:26, zhongzijian, null, null
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6e0a1219]

找了很长时间没有找到原因,最终通过排除定位到了问题,即:

SpringBoot 启动类添加了@ComponentScan有添加了@MapperScan,同时在Mapper.java类上添加了注解@Repository导致Mapper.java被@ComponentScan和@MapperScan都扫码了一次,重复扫码导致@Transactional失效便出现了如上异常。

解决方法:

1、Mapper.java不添加任何注解(避免被@ComponentScan扫描到),在添加@MapperScan扫码Mapper.java

示例:

@ComponentScan(basePackages = {"com.xxx"})
@MapperScan(basePackages = {"com.xxxx.Mapper"})

2、不是使用@MapperScan扫描,在Mapper.java添加@Mapper

示例:

@Mapper
public interface Test2Mapper

该解决方案适用于:SpringBoot2.0+Mybatis3.5

注意:不适用于SpringBoot+MybatisPlus

你可能感兴趣的:(mybatis,java,Transactional,Mapper重复扫描)