小编给大家分享一下SpringBoot中集成Mybatis+xml格式的sql配置文件操作示例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
最近一直在研究SpringBoot技术,由于项目需要,必须使用Mybatis持久化数据。所以就用SpringBoot集成Mybatis。
由于项目使用的是xml配置文件格式的SQL管理,所以SpringBoot必须配置Mybatis文件。但这样做的话又与SpringBoot的零xml配置冲突。
所以索性使用java类来配置Mybatis。
import java.util.Properties; import javax.sql.DataSource; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import com.github.pagehelper.PageHelper; import tk.mybatis.spring.mapper.MapperScannerConfigurer; /** * Mybatis & Mapper & PageHelper 配置 * * @file MybatisConfigurer.java * @author zoboy * @version 2.0.0 * @todo TODO Copyright(C), 2017 xi'an Coordinates Software Development Co., * Ltd. */ @Configuration public class MybatisConfigurer { static final String ALIASESPACKAG="com.cictec.cloud.bus.middleware.dc.common.biz.entity"; static final String MAPPERXMLPATH="classpath:sqlmapper/*.xml"; static final String BASEPACKAGE="com.cictec.cloud.bus.middleware.dc.mapper"; static final String DATABSAENAME="POSTGRESQL"; @Bean public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); //实体类的包名(根据你的项目自行修改) factory.setTypeAliasesPackage(ALIASESPACKAG); //配置分页插件,详情请查阅官方文档 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数 pageHelper.setProperties(properties); //添加插件 factory.setPlugins(new Interceptor[]{pageHelper}); //添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //*.mapper.xml的地址(根据你的项目自行修改) factory.setMapperLocations(resolver.getResources(MAPPERXMLPATH)); return factory.getObject(); } @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean"); //*.mapper(*.dao)的包名(根据你的项目自行修改) mapperScannerConfigurer.setBasePackage(BASEPACKAGE); //配置通用Mapper,详情请查阅官方文档 Properties properties = new Properties(); //tk.mybatis.mapper.common.Mapper properties.setProperty("mappers", "tk.mybatis.mapper.common.Mapper"); properties.setProperty("notEmpty", "false");//insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != '' //使用的数据库类型名称(MySQL,Oracle,Postgresql...) properties.setProperty("IDENTITY", DATABSAENAME); mapperScannerConfigurer.setProperties(properties); return mapperScannerConfigurer; } }
可以直接在你的项目中使用这个配置类,所要改动的地方有3处,我在代码中用注释标注了。
经测试,可以正常运行。
<?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.test.dao.StrategyDao"> <resultMap id="StrategyResultMap" type="com.test.entity.Strategy"> <result property="id" column="id"/> <result property="projectId" column="project_id"/> <result property="strategyType" column="strategy_type"/> <result property="strategyName" column="strategy_name"/> <result property="alias" column="alias"/> </resultMap> <select id="findNameList" resultType="java.util.Map" parameterType="com.test.entity.Strategy"> SELECT DISTINCT t.strategy_name strategyName,t.alias from test_strategy t WHERE t.project_id=#{projectId, jdbcType=INTEGER} AND t.del_status=0 AND t.strategy_type =#{strategyType} AND (t.strategy_name LIKE concat('%',#{strategyName,jdbcType=VARCHAR},'%') or t.alias LIKE concat('%',#{strategyName,jdbcType=VARCHAR},'%')) </select> </mapper>
@MyBatisRepository public interface StrategyDao extends ICrudDao<Strategy, Integer> { List<Map<String,Object>> findNameList(Strategy entity); }
public List<Map<String, Object>> findNameList(Strategy strategy) throws Exception { try { return dao.findNameList(strategy); } catch (Exception var3) { throw new MySqlException("P2101", "数据库执行异常", var3); } } ----------- public class MySqlException extends ServiceException { public MySqlException(String errorCode, Object[] args) { super(errorCode, args); } public MySqlException(String errorCode) { super(errorCode); } public MySqlException(String errorCode, String message) { super(errorCode, message); } public MySqlException(String errorCode, String message, Throwable cause) { super(errorCode, message, cause); } }
@RequestMapping("/nameList") public Map<String, Object> findNameList(@RequestBody Strategy strategy) throws Exception { try { return result(strategyService.findNameList(strategy)); } catch (Exception e) { throw e; } } ----------- public Map<String, Object> result(Object object) { Map<String, Object> result = new HashMap(); ResultUtil.addSuccessResult(result, object); return result; } ------- public class ResultUtil { public ResultUtil() { } public static void addSuccessResult(Map<String, Object> resultMap, Object data) { resultMap.put("result", "1"); resultMap.put("msg", "调用成功!"); resultMap.put("code", "200"); resultMap.put("data", data); } }
以上是“SpringBoot中集成Mybatis+xml格式的sql配置文件操作示例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。