SpringBoot集成Mybatis+xml格式的sql配置文件操作
作者:hzoboy 时间:2022-12-05 13:14:12
SpringBoot集成Mybatis+xml格式的sql配置文件
最近一直在研究SpringBoot技术,由于项目需要,必须使用Mybatis持久化数据。所以就用SpringBoot集成Mybatis。
由于项目使用的是xml配置文件格式的SQL管理,所以SpringBoot必须配置Mybatis文件。但这样做的话又与SpringBoot的零xml配置冲突。
所以索性使用java类来配置Mybatis。
下面是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处,我在代码中用注释标注了。
项目结构如下图所示:
经测试,可以正常运行。
Mybatis xml文件配置sql标准格式
1.Mapper.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="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>
2.Dao
@MyBatisRepository
public interface StrategyDao extends ICrudDao<Strategy, Integer> {
List<Map<String,Object>> findNameList(Strategy entity);
}
3.service
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);
}
}
4.Controller
@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);
}
}
来源:https://blog.csdn.net/u011051912/article/details/74295172
标签:SpringBoot,Mybatis,xml,sql
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MyBatisPlus3.x中使用代码生成器(全注释)
2022-04-06 19:34:38
![](https://img.aspxhome.com/file/2023/6/125656_0s.jpg)
详解MyBatis日志如何做到兼容所有常用的日志框架
2022-05-28 08:24:17
![](https://img.aspxhome.com/file/2023/4/78044_0s.png)
SpringBoot拦截器的配置使用介绍
2021-06-20 07:25:54
![](https://img.aspxhome.com/file/2023/5/92655_0s.png)
C++编程异常处理中try和throw以及catch语句的用法
2023-04-08 15:29:41
Android自定义SwipeRefreshLayout高仿微信朋友圈下拉刷新
2023-01-06 08:51:34
![](https://img.aspxhome.com/file/2023/0/139400_0s.gif)
C# 微信支付回调验签处理的实现
2021-07-27 01:57:34
三道java新手入门面试题,通往自由的道路--锁+Volatile
2023-09-04 20:33:42
![](https://img.aspxhome.com/file/2023/7/68717_0s.jpg)
Android 模仿QQ侧滑删除ListView功能示例
2023-10-27 21:03:43
SpringBoot+微信小程序实现文件上传与下载功能详解
2023-01-17 15:56:39
![](https://img.aspxhome.com/file/2023/2/97782_0s.jpg)
深入理解ThreadLocal工作原理及使用示例
2022-02-27 19:24:14
![](https://img.aspxhome.com/file/2023/6/62066_0s.png)
Spring Cache手动清理Redis缓存
2023-11-29 02:49:52
idea中如何使用git进行版本回退详解
2022-03-24 06:28:11
![](https://img.aspxhome.com/file/2023/2/101762_0s.jpg)
Spring自动装配之方法、构造器位置的自动注入操作
2021-11-30 23:28:40
c#中DataTable转List的2种方法示例
2022-05-10 20:51:09
js事件模型与自定义事件实例解析
2021-05-26 06:15:06
实例讲解Java读取一般文本文件和word文档的方法
2023-11-13 05:09:53
android使用PullToRefresh实现下拉刷新和上拉加载
2023-08-06 11:06:58
![](https://img.aspxhome.com/file/2023/5/85455_0s.png)
MyBatis多表关联查询的实现示例
2023-07-06 06:26:49
![](https://img.aspxhome.com/file/2023/8/88748_0s.jpg)
Android使用Websocket实现聊天室
2023-07-07 13:01:59
![](https://img.aspxhome.com/file/2023/6/60386_0s.png)
SpringBoot整合Mybatis的知识点汇总
2023-11-15 21:56:06