package com.iailab.framework.mybatis.config; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.iailab.framework.mybatis.core.handler.MybatisHandler; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.type.JdbcType; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; /** * @author houzhongjian * @Title: MyBatisConfiguration * @ProjectName design-parent * @Description: 解决独立启动某个服务时报错问题 No typehandler found for property sqlSessionTemplate * @date 2024/7/2 16:35 */ @Configuration public class MyBatisConfiguration { // 配置mapper的扫描,找到所有的mapper.xml映射文件 @Value("${iailab.info.base-package}") private String mapperLocations; // @Bean(name = "dataSource") // @ConfigurationProperties(prefix = "spring.datasource.test1") // @Primary // public DataSource dataSource() { // return DataSourceBuilder.create().build(); // } @Bean @Primary public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(DataSourceBuilder.create().build()); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations)); sqlSessionFactoryBean.setConfiguration(buildConfiguration()); return sqlSessionFactoryBean.getObject(); } @Bean @Primary public SqlSessionTemplate sqlSessionTemplate() throws Exception { return new SqlSessionTemplate(sqlSessionFactory()); } @Bean @Primary public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(DataSourceBuilder.create().build()); } private org.apache.ibatis.session.Configuration buildConfiguration() { org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(); configuration.getTypeHandlerRegistry().register(JSONObject.class, JdbcType.VARCHAR, MybatisHandler.class); configuration.getTypeHandlerRegistry().register(JSONArray.class, JdbcType.VARCHAR, MybatisHandler.class); return configuration; } }