SpringBoot集成Mybatis+xml格式的sql配置文件操作
SpringBoot集成Mybatis+xml格式的sql配置文件
最近一直在研究SpringBoot技術(shù),由于項(xiàng)目需要,必須使用Mybatis持久化數(shù)據(jù)。所以就用SpringBoot集成Mybatis。
由于項(xiàng)目使用的是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);
//實(shí)體類的包名(根據(jù)你的項(xiàng)目自行修改)
factory.setTypeAliasesPackage(ALIASESPACKAG);
//配置分頁插件,詳情請(qǐng)查閱官方文檔
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("pageSizeZero", "true");//分頁尺寸為0時(shí)查詢所有紀(jì)錄不再執(zhí)行分頁
properties.setProperty("reasonable", "true");//頁碼<=0 查詢第一頁,頁碼>=總頁數(shù)查詢最后一頁
properties.setProperty("supportMethodsArguments", "true");//支持通過 Mapper 接口參數(shù)來傳遞分頁參數(shù)
pageHelper.setProperties(properties);
//添加插件
factory.setPlugins(new Interceptor[]{pageHelper});
//添加XML目錄
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//*.mapper.xml的地址(根據(jù)你的項(xiàng)目自行修改)
factory.setMapperLocations(resolver.getResources(MAPPERXMLPATH));
return factory.getObject();
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
//*.mapper(*.dao)的包名(根據(jù)你的項(xiàng)目自行修改)
mapperScannerConfigurer.setBasePackage(BASEPACKAGE);
//配置通用Mapper,詳情請(qǐng)查閱官方文檔
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"表達(dá)式內(nèi)是否追加 and str != ''
//使用的數(shù)據(jù)庫類型名稱(MySQL,Oracle,Postgresql...)
properties.setProperty("IDENTITY", DATABSAENAME);
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
可以直接在你的項(xiàng)目中使用這個(gè)配置類,所要改動(dòng)的地方有3處,我在代碼中用注釋標(biāo)注了。
項(xiàng)目結(jié)構(gòu)如下圖所示:

經(jīng)測(cè)試,可以正常運(yùn)行。
Mybatis xml文件配置sql標(biāo)準(zhǔn)格式
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", "數(shù)據(jù)庫執(zhí)行異常", 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", "調(diào)用成功!");
resultMap.put("code", "200");
resultMap.put("data", data);
}
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實(shí)現(xiàn)的根據(jù)概率隨機(jī)中獎(jiǎng)測(cè)試類
這篇文章主要介紹了java實(shí)現(xiàn)的根據(jù)概率隨機(jī)中獎(jiǎng)測(cè)試類,結(jié)合完整實(shí)例形式詳細(xì)分析了java隨機(jī)數(shù)實(shí)現(xiàn)概率運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
Java字符編碼原理(動(dòng)力節(jié)點(diǎn)Java學(xué)院整理)
Java開發(fā)中,常常會(huì)遇到亂碼的問題,一旦遇到這種問題,常常比較煩惱,大家都不想承認(rèn)是自己的代碼問題,其實(shí)搞明白編碼的本質(zhì)過程就簡單多了,接下來小編給大家?guī)韏ava字符編碼原理,要求看看吧2017-04-04
編寫Spring MVC控制器的14個(gè)技巧(小結(jié))
這篇文章主要介紹了編寫Spring MVC控制器的14個(gè)技巧,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
AJAX Servlet實(shí)現(xiàn)數(shù)據(jù)異步交互的方法
本篇文章主要介紹了AJAX Servlet實(shí)現(xiàn)數(shù)據(jù)異步交互的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
關(guān)于Jedis的用法以及Jedis使用Redis事務(wù)
這篇文章主要介紹了關(guān)于Jedis的用法以及Jedis使用Redis事務(wù)問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
解決引用jip-common jar包,報(bào)401 Unauthorized錯(cuò)誤問題
這篇文章主要介紹了解決引用jip-common jar包,報(bào)401 Unauthorized錯(cuò)誤問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
關(guān)于JavaEE內(nèi)部類的部分注意事項(xiàng)
這篇文章主要介紹了關(guān)于JavaEE內(nèi)部類的部分注意事項(xiàng),將一個(gè)類定義在另一個(gè)類里面或者一個(gè)方法里面,這樣的類稱為內(nèi)部類,這是一種封裝思想,那么使用內(nèi)部類的時(shí)候要注意些什么呢,讓我們一起來看看吧2023-03-03

