淺析Mybatis Plus和Mybatis的區(qū)別
區(qū)別一
如果Mybatis Plus是扳手,那Mybatis Generator就是生產(chǎn)扳手的工廠。
通俗來(lái)講——
MyBatis:一種操作數(shù)據(jù)庫(kù)的框架,提供一種Mapper類,支持讓你用java代碼進(jìn)行增刪改查的數(shù)據(jù)庫(kù)操作,省去了每次都要手寫(xiě)sql語(yǔ)句的麻煩。但是!有一個(gè)前提,你得先在xml中寫(xiě)好sql語(yǔ)句,是不是很麻煩?于是有下面的↓
Mybatis Generator:自動(dòng)為Mybatis生成簡(jiǎn)單的增刪改查sql語(yǔ)句的工具,省去一大票時(shí)間,兩者配合使用,開(kāi)發(fā)速度快到飛起。至于標(biāo)題說(shuō)的↓
Mybatis Plus:國(guó)人團(tuán)隊(duì)苞米豆在Mybatis的基礎(chǔ)上開(kāi)發(fā)的框架,在Mybatis基礎(chǔ)上擴(kuò)展了許多功能,榮獲了2018最受歡迎國(guó)產(chǎn)開(kāi)源軟件第5名,當(dāng)然也有配套的↓
Mybatis Plus Generator:同樣為苞米豆開(kāi)發(fā),比Mybatis Generator更加強(qiáng)大,支持功能更多,自動(dòng)生成Entity、Mapper、Service、Controller等
總結(jié):
數(shù)據(jù)庫(kù)框架:Mybatis Plus > Mybatis
代碼生成器:Mybatis Plus Generator > Mybatis Generator
區(qū)別二
Mybatis-Plus是一個(gè)Mybatis的增強(qiáng)工具,它在Mybatis的基礎(chǔ)上做了增強(qiáng),卻不做改變。我們?cè)谑褂肕ybatis-Plus之后既可以使用Mybatis-Plus的特有功能,又能夠正常使用Mybatis的原生功能。Mybatis-Plus(以下簡(jiǎn)稱MP)是為簡(jiǎn)化開(kāi)發(fā)、提高開(kāi)發(fā)效率而生,但它也提供了一些很有意思的插件,比如SQL性能監(jiān)控、樂(lè)觀鎖、執(zhí)行分析等。
Mybatis雖然已經(jīng)給我們提供了很大的方便,但它還是有不足之處,實(shí)際上沒(méi)有什么東西是完美的,MP的存在就是為了稍稍彌補(bǔ)Mybatis的不足。在我們使用Mybatis時(shí)會(huì)發(fā)現(xiàn),每當(dāng)要寫(xiě)一個(gè)業(yè)務(wù)邏輯的時(shí)候都要在DAO層寫(xiě)一個(gè)方法,再對(duì)應(yīng)一個(gè)SQL,即使是簡(jiǎn)單的條件查詢、即使僅僅改變了一個(gè)條件都要在DAO層新增一個(gè)方法,針對(duì)這個(gè)問(wèn)題,MP就提供了一個(gè)很好的解決方案,之后我會(huì)進(jìn)行介紹。另外,MP的代碼生成器也是一個(gè)很有意思的東西,它可以讓我們避免許多重復(fù)性的工作,下面我將介紹如何在你的項(xiàng)目中集成MP。
一、 集成步驟↓:(首先,你要有個(gè)spring項(xiàng)目)
集成依賴,pom中加入依賴即可,不多說(shuō):
<!-- mybatis mybatis-plus mybatis-spring mvc --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
說(shuō)明:筆者使用的版本為:mybatis-plus.version=2.1-gamma,上邊的代碼中有兩個(gè)依賴,第一個(gè)是mybatis-plus核心依賴,第二個(gè)是使用代碼生成器時(shí)需要的模板引擎依賴,若果你不打算使用代碼生成器,此處可不引入。
注意:mybatis-plus的核心jar包中已集成了mybatis和mybatis-spring,所以為避免沖突,請(qǐng)勿再次引用這兩個(gè)jar包。
二、 在spring中配置MP:
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 配置數(shù)據(jù)源 --> <property name="dataSource" ref="dataSource" /> <!-- 自動(dòng)掃描 Xml 文件位置 --> <property name="mapperLocations" value="classpath*:com/ds/orm/mapper/**/*.xml" /> <!-- 配置 Mybatis 配置文件(可無(wú)) --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 配置包別名,支持通配符 * 或者 ; 分割 --> <property name="typeAliasesPackage" value="com.ds.orm.model" /> <!-- 枚舉屬性配置掃描,支持通配符 * 或者 ; 分割 --> <!-- <property name="typeEnumsPackage" value="com.baomidou.springmvc.entity.*.enums" /> --> <!-- 以上配置和傳統(tǒng) Mybatis 一致 --> <!-- MP 全局配置注入 --> <property name="globalConfig" ref="globalConfig" /> </bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- 主鍵策略配置 --> <!-- 可選參數(shù) AUTO->`0`("數(shù)據(jù)庫(kù)ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") --> <property name="idType" value="2" /> <!-- 數(shù)據(jù)庫(kù)類型配置 --> <!-- 可選參數(shù)(默認(rèn)mysql) MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2` HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005` SQLSERVER->`sqlserver` --> <property name="dbType" value="mysql" /> <!-- 全局表為下劃線命名設(shè)置 true --> <property name="dbColumnUnderline" value="true" /> <property name="sqlInjector"> <bean class="com.baomidou.mybatisplus.mapper.AutoSqlInjector" /> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <description>DAO接口所在包名,Spring會(huì)自動(dòng)查找其下的類</description> <property name="basePackage" value="com.ds.orm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 樂(lè)觀鎖插件 --> <bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor" /> <!-- xml mapper熱加載 sqlSessionFactory:session工廠 mapperLocations:mapper匹配路徑 enabled:是否開(kāi)啟動(dòng)態(tài)加載 默認(rèn):false delaySeconds:項(xiàng)目啟動(dòng)延遲加載時(shí)間 單位:秒 默認(rèn):10s sleepSeconds:刷新時(shí)間間隔 單位:秒 默認(rèn):20s --> <bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> <constructor-arg name="mapperLocations" value="classpath*:com/ds/orm/mapper/*/*.xml" /> <constructor-arg name="delaySeconds" value="10" /> <constructor-arg name="sleepSeconds" value="20" /> <constructor-arg name="enabled" value="true" /> </bean> <!-- 事務(wù) --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> 注意:只要做如上配置就可以正常使用mybatis了,不要重復(fù)配置。MP的配置和mybatis一樣,都是配置一個(gè)sqlSessionFactory,只是現(xiàn)在所配置的類在原本的SqlSessionFactoryBean基礎(chǔ)上做了增強(qiáng)。插件等配置請(qǐng)按需取舍。 插件配置,按需求配置就可以,此處把可以配置的插件都列了出來(lái),具體的請(qǐng)看代碼注釋: Java代碼 收藏代碼 <configuration> <settings> <setting name="logImpl" value="SLF4J" /> <!-- 字段為空時(shí)仍調(diào)用model的set方法或map的put方法 --> <setting name="callSettersOnNulls" value="true" /> </settings> <plugins> <!-- | 分頁(yè)插件配置 | 插件提供二種方言選擇:1、默認(rèn)方言 2、自定義方言實(shí)現(xiàn)類,兩者均未配置則拋出異常! | overflowCurrent 溢出總頁(yè)數(shù),設(shè)置第一頁(yè) 默認(rèn)false | optimizeType Count優(yōu)化方式 ( 版本 2.0.9 改為使用 jsqlparser 不需要配置 ) | --> <!-- 注意!! 如果要支持二級(jí)緩存分頁(yè)使用類 CachePaginationInterceptor 默認(rèn)、建議如下??! --> <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql" /> <!--<property name="sqlParser" ref="自定義解析類、可以沒(méi)有" /> <property name="localPage" value="默認(rèn) false 改為 true 開(kāi)啟了 pageHeper 支持、可以沒(méi)有" /> <property name="dialectClazz" value="自定義方言類、可以沒(méi)有" /> --> </plugin> <!-- SQL 執(zhí)行性能分析,開(kāi)發(fā)環(huán)境使用,線上不推薦。 maxTime 指的是 sql 最大執(zhí)行時(shí)長(zhǎng) --> <plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor"> <property name="maxTime" value="2000" /> <!--SQL是否格式化 默認(rèn)false --> <property name="format" value="true" /> </plugin> <!-- SQL 執(zhí)行分析攔截器 stopProceed 發(fā)現(xiàn)全表執(zhí)行 delete update 是否停止運(yùn)行 該插件只用于開(kāi)發(fā)環(huán)境,不建議生產(chǎn)環(huán)境使用。。。 --> <plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor"> <property name="stopProceed" value="false" /> </plugin> </plugins> </configuration>
注意:執(zhí)行分析攔截器和性能分析推薦只在開(kāi)發(fā)時(shí)調(diào)試程序使用,為保證程序性能和穩(wěn)定性,建議在生產(chǎn)環(huán)境中注釋掉這兩個(gè)插件。
數(shù)據(jù)源:(此處使用druid)
<!-- 配置數(shù)據(jù)源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- <property name="driverClassName" value="${jdbc.driverClassName}" /> --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testOnReturn" value="${jdbc.testOnReturn}" /> <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> <!-- <property name="logAbandoned" value="${jdbc.logAbandoned}" /> --> <property name="filters" value="${jdbc.filters}" /> <!-- 關(guān)閉abanded連接時(shí)輸出錯(cuò)誤日志 --> <property name="logAbandoned" value="true" /> <property name="proxyFilters"> <list> <ref bean="log-filter"/> </list> </property> <!-- 監(jiān)控?cái)?shù)據(jù)庫(kù) --> <!-- <property name="filters" value="stat" /> --> <!-- <property name="filters" value="mergeStat" />--> </bean>
到此,MP已經(jīng)集成進(jìn)我們的項(xiàng)目中了,下面將介紹它是如何簡(jiǎn)化我們的開(kāi)發(fā)的。
**
三、 簡(jiǎn)單的CURD操作↓:
**
假設(shè)我們有一張user表,且已經(jīng)建立好了一個(gè)與此表對(duì)應(yīng)的實(shí)體類User,我們來(lái)介紹對(duì)user的簡(jiǎn)單增刪改查操作。
建立DAO層接口。我們?cè)谑褂闷胀ǖ膍ybatis時(shí)會(huì)建立一個(gè)DAO層接口,并對(duì)應(yīng)一個(gè)xml用來(lái)寫(xiě)SQL。在這里我們同樣要建立一個(gè)DAO層接口,但是若無(wú)必要,我們甚至不需要建立xml,就可以進(jìn)行資源的CURD操作了,我們只需要讓我們建立的DAO繼承MP提供的BaseMapper<?>即可:
public interface UserMapper extends BaseMapper { }
然后在我們需要做數(shù)據(jù)CURD時(shí),像下邊這樣就好了:
// 初始化 影響行數(shù) int result = 0; // 初始化 User 對(duì)象 User user = new User(); // 插入 User (插入成功會(huì)自動(dòng)回寫(xiě)主鍵到實(shí)體類) user.setName(“Tom”); result = userMapper.insert(user); // 更新 User user.setAge(18); result = userMapper.updateById(user);//user要設(shè)置id哦,具體的在下邊我會(huì)詳細(xì)介紹 // 查詢 User User exampleUser = userMapper.selectById(user.getId()); // 查詢姓名為‘張三'的所有用戶記錄 List userList = userMapper.selectList( new EntityWrapper().eq(“name”, “張三”) ); // 刪除 User result = userMapper.deleteById(user.getId());
方便吧?如果只使用mybatis可是要寫(xiě)4個(gè)SQL和4個(gè)方法喔,當(dāng)然了,僅僅上邊這幾個(gè)方法還遠(yuǎn)遠(yuǎn)滿足不了我們的需求,請(qǐng)往下看:
**
多條件分頁(yè)查詢:
**
// 分頁(yè)查詢 10 條姓名為‘張三'、性別為男,且年齡在18至50之間的用戶記錄
List<User> userList = userMapper.selectPage( new Page<User>(1, 10), new EntityWrapper<User>().eq("name", "張三") .eq("sex", 0) .between("age", "18", "50") );
/**等價(jià)于SELECT * *FROM sys_user *WHERE (name=‘張三' AND sex=0 AND age BETWEEN ‘18' AND ‘50') *LIMIT 0,10 */
下邊這個(gè),多條件構(gòu)造器。其實(shí)對(duì)于條件過(guò)于復(fù)雜的查詢,筆者還是建議使用原生mybatis的方式實(shí)現(xiàn),易于維護(hù)且邏輯清晰,如果所有的數(shù)據(jù)操作都強(qiáng)行使用MP,就失去了MP簡(jiǎn)化開(kāi)發(fā)的意義了。所以在使用時(shí)請(qǐng)按實(shí)際情況取舍,在這里還是先介紹一下。
public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) { if (null != entityWrapper) { entityWrapper.orderBy(page.getOrderByField(), page.isAsc());//排序 } page.setRecords(baseMapper.selectPage(page, entityWrapper));//將查詢結(jié)果放入page中 return page; }
**條件構(gòu)造一(上邊方法的entityWrapper參數(shù)):**
public void testTSQL11() { /* * 實(shí)體帶查詢使用方法 輸出看結(jié)果 */ EntityWrapper<User> ew = new EntityWrapper<User>(); ew.setEntity(new User(1)); ew.where("user_name={0}", "'zhangsan'").and("id=1") .orNew("user_status={0}", "0").or("status=1") .notLike("user_nickname", "notvalue") .andNew("new=xx").like("hhh", "ddd") .andNew("pwd=11").isNotNull("n1,n2").isNull("n3") .groupBy("x1").groupBy("x2,x3") .having("x1=11").having("x3=433") .orderBy("dd").orderBy("d1,d2"); System.out.println(ew.getSqlSegment()); }
**條件構(gòu)造二(同上):**
int buyCount = selectCount(Condition.create() .setSqlSelect(“sum(quantity)”) .isNull(“order_id”) .eq(“user_id”, 1) .eq(“type”, 1) .in(“status”, new Integer[]{0, 1}) .eq(“product_id”, 1) .between(“created_time”, startDate, currentDate) .eq(“weal”, 1));
自定義條件使用entityWrapper:
List selectMyPage(RowBounds rowBounds, @Param(“ew”) Wrapper wrapper); SELECT * FROM user ${ew.sqlSegment }
*注意:此處不用擔(dān)心SQL注入,MP已對(duì)ew做了字符串轉(zhuǎn)義處理。其實(shí)在使用MP做數(shù)據(jù)CURD時(shí),還有另外一個(gè)方法,AR(ActiveRecord ),很簡(jiǎn)單,讓我們的實(shí)體類繼承MP提供Model<?>就好了,這和我們常用的方法可能會(huì)有些不同,下邊簡(jiǎn)單說(shuō)一下吧:*
//實(shí)體類 @TableName(“sys_user”) // 注解指定表名 public class User extends Model { … // fields … // getter and setter /** 指定主鍵 */ @Override protected Serializable pkVal() { //一定要指定主鍵哦 return this.id; } }
下邊就是CURD操作了:
// 初始化 成功標(biāo)識(shí) boolean result = false; // 初始化 User User user = new User(); // 保存 User user.setName(“Tom”); result = user.insert(); // 更新 User user.setAge(18); result = user.updateById(); // 查詢 User User exampleUser = t1.selectById(); // 查詢姓名為‘張三'的所有用戶記錄 List userList1 = user.selectList( new EntityWrapper().eq(“name”, “張三”) ); // 刪除 User result = t2.deleteById(); // 分頁(yè)查詢 10 條姓名為‘張三'、性別為男,且年齡在18至50之間的用戶記錄 List userList = user.selectPage( new Page(1, 10), new EntityWrapper().eq(“name”, “張三”) .eq(“sex”, 0) .between(“age”, “18”, “50”) ).getRecords();
就是這樣了,可能你會(huì)說(shuō)MP封裝的有些過(guò)分了,這樣做會(huì)分散數(shù)據(jù)邏輯到不同的層面中,難以管理,使代碼難以理解。其實(shí)確實(shí)是這樣,這就需要你在使用的時(shí)候注意一下了,在簡(jiǎn)化開(kāi)發(fā)的同時(shí)也要保證你的代碼層次清晰,做一個(gè)戰(zhàn)略上的設(shè)計(jì)或者做一個(gè)取舍與平衡。
**
其實(shí)上邊介紹的功能也不是MP的全部啦,下邊介紹一下MP最有意思的模塊——代碼生成器。
**
步驟↓:
如上邊所說(shuō),使用代碼生成器一定要引入velocity-engine-core(模板引擎)這個(gè)依賴。
準(zhǔn)備工作:
選擇主鍵策略,就是在上邊最開(kāi)始時(shí)候我介紹MP配置時(shí)其中的這項(xiàng)配置,如果你不記得了,請(qǐng)上翻!MP提供了如下幾個(gè)主鍵策略: 值 描述
IdType.AUTO數(shù)據(jù)庫(kù)ID自增
IdType.INPUT用戶輸入ID
IdType.ID_WORKER全局唯一ID,內(nèi)容為空自動(dòng)填充(默認(rèn)配置)
IdType.UUID全局唯一ID,內(nèi)容為空自動(dòng)填充
MP默認(rèn)使用的是ID_WORKER,這是MP在Sequence的基礎(chǔ)上進(jìn)行部分優(yōu)化,用于產(chǎn)生全局唯一ID。
表及字段命名策略選擇,同上,還是在那個(gè)配置中。下邊這段復(fù)制至MP官方文檔:
在MP中,我們建議數(shù)據(jù)庫(kù)表名采用下劃線命名方式,而表字段名采用駝峰命名方式。
這么做的原因是為了避免在對(duì)應(yīng)實(shí)體類時(shí)產(chǎn)生的性能損耗,這樣字段不用做映射就能直接和實(shí)體類對(duì)應(yīng)。當(dāng)然如果項(xiàng)目里不用考慮這點(diǎn)性能損耗,那么你采用下滑線也是沒(méi)問(wèn)題的,只需要在生成代碼時(shí)配置dbColumnUnderline屬性就可以。
建表(命名規(guī)則依照剛才你所配置的,這會(huì)影響生成的代碼的類名、字段名是否正確)。
執(zhí)行下邊的main方法,生成代碼:
import java.util.HashMap; import java.util.Map; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; /** * <p> * 代碼生成器演示 * </p> */ public class MpGenerator { /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("D://"); gc.setFileOverride(true); gc.setActiveRecord(true);// 不需要ActiveRecord特性的請(qǐng)改為false gc.setEnableCache(false);// XML 二級(jí)緩存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(false);// XML columList // .setKotlin(true) 是否生成 kotlin 代碼 gc.setAuthor("Yanghu"); // 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sDao"); // gc.setServiceName("MP%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // 數(shù)據(jù)源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert(){ // 自定義數(shù)據(jù)庫(kù)表字段類型轉(zhuǎn)換【可選】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("轉(zhuǎn)換類型:" + fieldType); // 注意!!processTypeConvert 存在默認(rèn)類型轉(zhuǎn)換,如果不是你要的效果請(qǐng)自定義返回、非如下直接返回。 return super.processTypeConvert(fieldType); } }); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("521"); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大寫(xiě)命名 ORACLE 注意 strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此處可以修改為您的表前綴 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 // strategy.setInclude(new String[] { "user" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定義實(shí)體父類 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // 自定義實(shí)體,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定義 mapper 父類 // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); // 自定義 service 父類 // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); // 自定義 service 實(shí)現(xiàn)類父類 // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // 自定義 controller 父類 // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // 【實(shí)體】是否生成字段常量(默認(rèn) false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false) // public User setName(String name) {this.name = name; return this;} // strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.baomidou"); pc.setModuleName("test"); mpg.setPackageInfo(pc); // 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無(wú)】 InjectionConfig cfg = 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); } }; // 自定義 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); focList.add(new FileOutConfig("/template/list.jsp.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸入文件名稱 return "D://my_" + tableInfo.getEntityName() + ".jsp"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 調(diào)整 xml 生成目錄演示 focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄 TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc); // 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內(nèi)容修改, // 放置自己項(xiàng)目的 src/main/resources/templates 目錄下, 默認(rèn)名稱一下可以不配置,也可以自定義模板名稱 // TemplateConfig tc = new TemplateConfig(); // tc.setController("..."); // tc.setEntity("..."); // tc.setMapper("..."); // tc.setXml("..."); // tc.setService("..."); // tc.setServiceImpl("..."); // 如上任何一個(gè)模塊如果設(shè)置 空 OR Null 將不生成該模塊。 // mpg.setTemplate(tc); // 執(zhí)行生成 mpg.execute(); // 打印注入設(shè)置【可無(wú)】 System.err.println(mpg.getCfg().getMap().get("abc")); } }
說(shuō)明:中間的內(nèi)容請(qǐng)自行修改,注釋很清晰。
成功生成代碼,將生成的代碼拷貝到你的項(xiàng)目中就可以了,這個(gè)東西節(jié)省了我們大量的時(shí)間和精力!
以下是注解說(shuō)明,摘自官方文檔: 注解說(shuō)明**
表名注解 @TableName
com.baomidou.mybatisplus.annotations.TableName
值 描述
value表名( 默認(rèn)空 )
resultMapxml 字段映射 resultMap ID
主鍵注解 @TableId
com.baomidou.mybatisplus.annotations.TableId
值 描述
value字段值(駝峰命名方式,該值可無(wú))
type主鍵 ID 策略類型( 默認(rèn) INPUT ,全局開(kāi)啟的是 ID_WORKER )
暫不支持組合主鍵
字段注解 @TableField
com.baomidou.mybatisplus.annotations.TableField
值 描述
value字段值(駝峰命名方式,該值可無(wú))
el詳看注釋說(shuō)明
exist是否為數(shù)據(jù)庫(kù)表字段( 默認(rèn) true 存在,false 不存在 )
strategy字段驗(yàn)證 ( 默認(rèn) 非 null 判斷,查看 com.baomidou.mybatisplus.enums.FieldStrategy )
fill字段填充標(biāo)記 ( FieldFill, 配合自動(dòng)填充使用 )
字段填充策略 FieldFill
值 描述
DEFAULT默認(rèn)不處理
INSERT插入填充字段
UPDATE更新填充字段
INSERT_UPDATE插入和更新填充字段
序列主鍵策略 注解 @KeySequence
com.baomidou.mybatisplus.annotations.KeySequence
值 描述
value序列名
clazzid的類型
樂(lè)觀鎖標(biāo)記注解 @Version
com.baomidou.mybatisplus.annotations.Version
排除非表字段、查看文檔常見(jiàn)問(wèn)題部分!
總結(jié):
MP的宗旨是簡(jiǎn)化開(kāi)發(fā),但是它在提供方便的同時(shí)卻容易造成代碼層次混亂,我們可能會(huì)把大量數(shù)據(jù)邏輯寫(xiě)到service層甚至contoller層中,使代碼難以閱讀。凡事過(guò)猶不及,在使用MP時(shí)一定要做分析,不要將所有數(shù)據(jù)操作都交給MP去實(shí)現(xiàn)。畢竟MP只是mybatis的增強(qiáng)工具,它并沒(méi)有侵入mybatis的原生功能,在使用MP的增強(qiáng)功能的同時(shí),原生mybatis的功能依然是可以正常使用的
相關(guān)文章
java+sqlserver實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要介紹了利用java和sqlserver實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),違章內(nèi)容主要建立了與sqlserver數(shù)據(jù)庫(kù)的連接開(kāi)始展開(kāi)內(nèi)容,能學(xué)到了解JDBC執(zhí)行SQL的語(yǔ)法,需要的朋友可以參考一下2021-12-12java擴(kuò)展Hibernate注解支持java8新時(shí)間類型
這篇文章主要介紹了java擴(kuò)展Hibernate注解支持java8新時(shí)間類型,需要的朋友可以參考下2014-04-04Java實(shí)現(xiàn)高并發(fā)秒殺的幾種方式
高并發(fā)場(chǎng)景在現(xiàn)場(chǎng)的日常工作中很常見(jiàn),本文主要介紹了Java實(shí)現(xiàn)高并發(fā)秒殺的幾種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05Java servlet后端開(kāi)發(fā)超詳細(xì)教程
Servlet指在服務(wù)器端執(zhí)行的一段Java代碼,可以接收用戶的請(qǐng)求和返回給用戶響應(yīng)結(jié)果,下面這篇文章主要給大家介紹了關(guān)于Java.servlet生命周期的相關(guān)資料,需要的朋友可以參考下2023-02-02