中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

SpringBoot | 第九章:Mybatis-plus的集成和使用

2018-08-19    來源:importnew

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬Linux鏡像隨意使用

前言

本章節(jié)開始介紹數(shù)據(jù)訪問方面的相關(guān)知識(shí)點(diǎn)。對(duì)于后端開發(fā)者而言,和數(shù)據(jù)庫打交道是每天都在進(jìn)行的,所以一個(gè)好用的ORM框架是很有必要的。目前,絕大部分公司都選擇MyBatis框架作為底層數(shù)據(jù)庫持久化框架。

多說幾句

看著現(xiàn)在Mybatis框架的大行其道,讓我不禁想起,大學(xué)時(shí)期,當(dāng)時(shí)還是hibernate的時(shí)代,現(xiàn)在基本已經(jīng)忘記了。而當(dāng)時(shí),Mybatis的前身iBatis還在書中的某個(gè)章節(jié)出現(xiàn)過。當(dāng)時(shí)大學(xué)老師的意思是:目前國(guó)內(nèi)基本沒有使用iBatis的公司,所以這一章節(jié)略過,略,過。。,F(xiàn)在對(duì)這個(gè)還記憶猶新,看著現(xiàn)在Mybatis大行其道,不禁令人唏噓呀。

Mybatis-Plus

Mybatis-Plus(簡(jiǎn)稱MP)是一個(gè) Mybatis 的增強(qiáng)工具,在 Mybatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開發(fā)、提高效率而生。

官方網(wǎng)站:http://mp.baomidou.com

簡(jiǎn)單來說,Mybatis-PlusMybatis的增強(qiáng)工具包,其簡(jiǎn)化了CRUD操作,提供了代碼生成器,強(qiáng)大的條件構(gòu)造器(這是我最喜歡的一個(gè)),同時(shí)內(nèi)置了多個(gè)實(shí)用插件:標(biāo)配的分頁插件、性能分析插件、全局?jǐn)r截插件等。使得開發(fā)過程中,基本的范式代碼都一句話解決了,省去了很多重復(fù)的操作(程序猿存在的意義呢,說好的讓我們搬磚呢!)。

SpringBoot集成

這里選用的mybatis-plus版本為:2.1.9,
mybatisplus-spring-boot-starter版本為:1.0.5。
對(duì)應(yīng)Mybatis版本為:3.4.5

0. 這里以u(píng)ser表為例子,數(shù)據(jù)庫為mysql

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) DEFAULT NULL COMMENT '唯一標(biāo)示',
  `code` varchar(20) DEFAULT NULL COMMENT '編碼',
  `name` varchar(64) DEFAULT NULL COMMENT '名稱',
  `status` char(1) DEFAULT '1' COMMENT '狀態(tài) 1啟用 0 停用',
  `gmt_create` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
  `gmt_modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時(shí)間'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1. pom依賴:

 <!--mybatis plus -->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatisplus-spring-boot-starter</artifactId>
	<version>1.0.5</version>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus</artifactId>
	<version>2.1.9</version>
</dependency>

2. 配置文件(當(dāng)然也可以直接使用@Bean的方式進(jìn)行或者通過application配置文件進(jìn)行,詳見官網(wǎng))
spring-mybatis.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--創(chuàng)建jdbc數(shù)據(jù)源 這里直接使用阿里的druid數(shù)據(jù)庫連接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${mysql.driver}"/>
        <property name="url" value="${mysql.url}"/>
        <property name="username" value="${mysql.username}"/>
        <property name="password" value="${mysql.password}"/>
        <!-- 初始化連接大小 -->
        <property name="initialSize" value="0"/>
        <!-- 連接池最大使用連接數(shù)量 -->
        <property name="maxActive" value="20"/>
        <!-- 連接池最大空閑 -->
        <property name="maxIdle" value="20"/>
        <!-- 連接池最小空閑 -->
        <property name="minIdle" value="0"/>
        <!-- 獲取連接最大等待時(shí)間 -->
        <property name="maxWait" value="60000"/>

        <property name="validationQuery" value="${validationQuery}"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="testWhileIdle" value="true"/>

        <!-- 配置間隔多久才進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000"/>
        <!-- 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000"/>

        <!-- 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="true"/>
        <!-- 1800秒,也就是30分鐘 -->
        <property name="removeAbandonedTimeout" value="1800"/>
        <!-- 關(guān)閉abanded連接時(shí)輸出錯(cuò)誤日志 -->
        <property name="logAbandoned" value="true"/>

        <!-- 監(jiān)控?cái)?shù)據(jù)庫 -->
        <property name="filters" value="mergeStat"/>
    </bean>

    <!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 可通過注解控制事務(wù) -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--mybatis-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
		<!-- 自動(dòng)掃描mapper.xml文件,支持通配符 -->
        <property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
		<!-- 配置文件,比如參數(shù)配置(是否啟動(dòng)駝峰等)、插件配置等 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
		<!-- 啟用別名,這樣就無需寫全路徑類名了,具體可自行查閱資料 -->
        <property name="typeAliasesPackage" value="cn.lqdev.learning.springboot.chapter9.biz.entity"/>
        <!-- MP 全局配置注入 -->
        <property name="globalConfig" ref="globalConfig"/>
    </bean>
    <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
        <!--
            AUTO->`0`("數(shù)據(jù)庫ID自增")QW
             INPUT->`1`(用戶輸入ID")
            ID_WORKER->`2`("全局唯一ID")
            UUID->`3`("全局唯一ID")
        -->
        <property name="idType" value="3" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 自動(dòng)掃描包路徑,接口自動(dòng)注冊(cè)為一個(gè)bean類 -->
        <property name="basePackage" value="cn.lqdev.learning.springboot.chapter9.biz.dao"/>
    </bean>

</beans>

3. 編寫啟動(dòng)類,應(yīng)用啟動(dòng)時(shí)自動(dòng)加載配置xml文件

/**
 *  mybatisPlus 配置類,使其加載配置文件
 * @author oKong
 *
 */
@Configuration
@ImportResource(locations = {"classpath:/mybatis/spring-mybatis.xml"})
//@MapperScan("cn.lqdev.learning.springboot.chapter9.biz.dao")
//@EnableTransactionManagement
public class MybatisPlusConfig {

}

至此,mybatis-plus就配置完成了,接下來,利用代碼生成器一次性創(chuàng)建所需的dao、mapper、通用CRUDservice類。

4. 編寫代碼生成器類

由于生成器依賴velocity模版引擎,故需要加入依賴:

<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity-engine-core</artifactId>
	<version>2.0</version>
	<scope>test</scope>
</dependency>

MysqlGenerator,此類較長(zhǎng),相關(guān)配置可根據(jù)實(shí)際情況信息修改替換。

public class MysqlGenerator {

	private static final String PACKAGE_NAME = "cn.lqdev.learning.springboot.chapter9";
	private static final String MODULE_NAME = "biz";
	private static final String OUT_PATH = "D:\\develop\\code";
	private static final String AUTHOR = "oKong";

	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://127.0.0.1:3306/learning?useUnicode=true&characterEncoding=UTF-8";
	private static final String USER_NAME = "root";
	private static final String PASSWORD = "123456";

	/**
	 * <p>
	 * MySQL 生成演示
	 * </p>
	 */
	public static void main(String[] args) {
		// 自定義需要填充的字段
		List<TableFill> tableFillList = new ArrayList<TableFill>();

		// 代碼生成器
		AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
				// 全局配置
				new GlobalConfig().setOutputDir(OUT_PATH)// 輸出目錄
						.setFileOverride(true)// 是否覆蓋文件
						.setActiveRecord(true)// 開啟 activeRecord 模式
						.setEnableCache(false)// XML 二級(jí)緩存
						.setBaseResultMap(false)// XML ResultMap
						.setBaseColumnList(true)// XML columList
						.setAuthor(AUTHOR)
						// 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性!
						.setXmlName("%sMapper").setMapperName("%sDao")
		// .setServiceName("MP%sService")
		// .setServiceImplName("%sServiceDiy")
		// .setControllerName("%sAction")
		).setDataSource(
				// 數(shù)據(jù)源配置
				new DataSourceConfig().setDbType(DbType.MYSQL)// 數(shù)據(jù)庫類型
						.setTypeConvert(new MySqlTypeConvert() {
							// 自定義數(shù)據(jù)庫表字段類型轉(zhuǎn)換【可選】
							@Override
							public DbColumnType processTypeConvert(String fieldType) {
								System.out.println("轉(zhuǎn)換類型:" + fieldType);
								// if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
								// return DbColumnType.BOOLEAN;
								// }
								return super.processTypeConvert(fieldType);
							}
						}).setDriverName(DRIVER).setUsername(USER_NAME).setPassword(PASSWORD).setUrl(URL))
				.setStrategy(
						// 策略配置
						new StrategyConfig()
								// .setCapitalMode(true)// 全局大寫命名
								.setDbColumnUnderline(true)// 全局下劃線命名
								// .setTablePrefix(new String[]{"unionpay_"})// 此處可以修改為您的表前綴
								.setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
								// .setInclude(new String[] {"citycode_org"}) // 需要生成的表
								// .setExclude(new String[]{"test"}) // 排除生成的表
								// 自定義實(shí)體,公共字段
								// .setSuperEntityColumns(new String[]{"test_id"})
								.setTableFillList(tableFillList)
								// 自定義實(shí)體父類
								// .setSuperEntityClass("com.baomidou.demo.common.base.BsBaseEntity")
								// // 自定義 mapper 父類
								// .setSuperMapperClass("com.baomidou.demo.common.base.BsBaseMapper")
								// // 自定義 service 父類
								// .setSuperServiceClass("com.baomidou.demo.common.base.BsBaseService")
								// // 自定義 service 實(shí)現(xiàn)類父類
								// .setSuperServiceImplClass("com.baomidou.demo.common.base.BsBaseServiceImpl")
								// 自定義 controller 父類
								// .setSuperControllerClass("com.baomidou.demo.TestController")
								// 【實(shí)體】是否生成字段常量(默認(rèn) false)
								// public static final String ID = "test_id";
								.setEntityColumnConstant(true)
								// 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false)
								// public User setName(String name) {this.name = name; return this;}
								.setEntityBuilderModel(true)
								// 【實(shí)體】是否為lombok模型(默認(rèn) false)<a href="https://projectlombok.org/">document</a>
								.setEntityLombokModel(true)
				// Boolean類型字段是否移除is前綴處理
				// .setEntityBooleanColumnRemoveIsPrefix(true)
				// .setRestControllerStyle(true)
				// .setControllerMappingHyphenStyle(true)
				).setPackageInfo(
						// 包配置
						new PackageConfig().setModuleName(MODULE_NAME).setParent(PACKAGE_NAME)// 自定義包路徑
								.setController("controller")// 這里是控制器包名,默認(rèn) web
								.setXml("mapper").setMapper("dao")

				).setCfg(
						// 注入自定義配置,可以在 VM 中使用 cfg.abc 設(shè)置的值
						new InjectionConfig() {
							@Override
							public void initMap() {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
								this.setMap(map);
							}
						}.setFileOutConfigList(
								Collections.<FileOutConfig>singletonList(new FileOutConfig("/templates/mapper.xml.vm") {
									// 自定義輸出文件目錄
									@Override
									public String outputFile(TableInfo tableInfo) {
										return OUT_PATH + "/xml/" + tableInfo.getEntityName() + "Mapper.xml";
									}
								})))
				.setTemplate(
						// 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄
						new TemplateConfig().setXml(null)
		// 自定義模板配置,模板可以參考源碼 /mybatis-plus/src/main/resources/template 使用 copy
		// 至您項(xiàng)目 src/main/resources/template 目錄下,模板名稱也可自定義如下配置:
		// .setController("...");
		// .setEntity("...");
		// .setMapper("...");
		// .setXml("...");
		// .setService("...");
		// .setServiceImpl("...");
		);

		// 執(zhí)行生成
		mpg.execute();
	}

}

運(yùn)行后即可,省了多少事!

簡(jiǎn)單實(shí)例

簡(jiǎn)單演示下增刪改查及分頁的使用。

使用分頁時(shí),mybatis-config.xml需要加入分頁插件:PerformanceInterceptor

<plugins>
  <!-- 分頁插件配置 -->
  <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor"></plugin>
</plugins>

編寫控制層

/**
 * 用戶控制層 簡(jiǎn)單演示增刪改查及分頁
 * @author oKong
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	IUserService userService;

	@PostMapping("add")
    //正常業(yè)務(wù)時(shí), 需要在user類里面進(jìn)行事務(wù)控制,控制層一般不進(jìn)行業(yè)務(wù)控制的。
	//@Transactional(rollbackFor = Exception.class)
	public Map<String,String> addUser(@Valid @RequestBody UserReq userReq){

		User user = new User();
		user.setCode(userReq.getCode());
		user.setName(userReq.getName());
		//由于設(shè)置了主鍵策略 id可不用賦值 會(huì)自動(dòng)生成
		//user.setId(0L);
		userService.insert(user);
		Map<String,String> result = new HashMap<String,String>();
		result.put("respCode", "01");
		result.put("respMsg", "新增成功");
		//事務(wù)測(cè)試
		//System.out.println(1/0);
		return result;
	}

	@PostMapping("update")
	public Map<String,String> updateUser(@Valid @RequestBody UserReq userReq){

		if(userReq.getId() == null || "".equals(userReq.getId())) {
			throw new CommonException("0000", "更新時(shí)ID不能為空");
		}
		User user = new User();
		user.setCode(userReq.getCode());
		user.setName(userReq.getName());
		user.setId(Long.parseLong(userReq.getId()));		
		userService.updateById(user);
		Map<String,String> result = new HashMap<String,String>();
		result.put("respCode", "01");
		result.put("respMsg", "更新成功");
		return result;
	}

	@GetMapping("/get/{id}")
	public Map<String,Object> getUser(@PathVariable("id") String id){
		//查詢
		User user = userService.selectById(id);
		if(user == null) {
			throw new CommonException("0001", "用戶ID:" + id + ",未找到");
		}
		UserResp resp = UserResp.builder()
				.id(user.getId().toString())
				.code(user.getCode())
				.name(user.getName())
				.status(user.getStatus())
				.build();
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("respCode", "01");
		result.put("respMsg", "成功");
		result.put("data", resp);
		return result;
	}

	@GetMapping("/page")
	public Map<String,Object> pageUser(int current, int size){
		//分頁
		Page<User> page = new Page<>(current, size);
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("respCode", "01");
		result.put("respMsg", "成功");
		result.put("data", userService.selectPage(page));
		return result;
	}		
}

啟動(dòng)應(yīng)用后,使用postman依次訪問對(duì)應(yīng)的url地址即可。

數(shù)據(jù)庫:

分頁

由于配置了分析插件,控制臺(tái)會(huì)輸出執(zhí)行的sql語句

其他的就不一一貼圖了。

關(guān)于事務(wù)

正常情況下,只需要在服務(wù)層中加入@Transactional即可,事務(wù)相關(guān)的此章節(jié)不進(jìn)行闡述,之后有機(jī)會(huì)會(huì)專門拿一個(gè)章節(jié)來說明下。

示例中為了方便,直接在控制層中加入了@Transactional進(jìn)行事務(wù)測(cè)試,正式開發(fā)過程中,強(qiáng)烈建議在服務(wù)層進(jìn)行業(yè)務(wù)控制,控制層一般上是進(jìn)行邏輯判斷的!

實(shí)體對(duì)象字段為枚舉類

可能在實(shí)際開發(fā)中,大家會(huì)碰到,為了方便,一些類型、狀態(tài)字段會(huì)編寫成枚舉類型,比如啟用狀態(tài):DISABLE(“0”),ENABLE(“1”)。此時(shí)可通過配置typeHandlers進(jìn)行自定義類型的處理,這里簡(jiǎn)單以EnumOrdinalTypeHandler(存儲(chǔ)enum類里的序號(hào)值)進(jìn)行示例,當(dāng)然也可根據(jù)需要進(jìn)行自定義處理器的編寫,比如編寫一個(gè)通用的枚舉轉(zhuǎn)換器等,其他相關(guān)知識(shí)點(diǎn),大家可自行谷歌。

StatusEnums

public enum StatusEnum {

	DISABLE,
	ENABLE;

}

將user對(duì)象修改成枚舉類型

/**
 * 狀態(tài)1 啟用 0 停用
 */
private StatusEnum status;

配置文件mybatis-config.xml加入處理類

<typeHandlers>
   <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler"
     javaType="cn.lqdev.learning.springboot.chapter9.biz.entity.StatusEnum"/>
</typeHandlers>

之后就會(huì)自動(dòng)進(jìn)行轉(zhuǎn)換了。大家可下載示例,進(jìn)行實(shí)際操作下。

總結(jié)

本章節(jié)主要是對(duì)Mybatis-plus的集成和簡(jiǎn)單使用進(jìn)行了說明,詳細(xì)的用法,可到官網(wǎng)查看,官網(wǎng)有詳細(xì)的使用指南,這里就不班門弄斧了。至此,對(duì)于一般的開發(fā)需求基本上都可以滿足了。接下來的章節(jié)會(huì)重點(diǎn)講解其他配套工具的使用,敬請(qǐng)期待!

最后

目前互聯(lián)網(wǎng)上很多大佬都有springboot系列教程,如有雷同,請(qǐng)多多包涵了。本文是作者在電腦前一字一句敲的,每一步都是實(shí)踐的。若文中有所錯(cuò)誤之處,還望提出,謝謝。

標(biāo)簽: isp Mysql 代碼 谷歌 互聯(lián)網(wǎng) 開發(fā)者 數(shù)據(jù)庫

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:SpringBoot | 第十章:Swagger2的集成和使用

下一篇:Linux查看分區(qū)文件系統(tǒng)類型總結(jié)