導讀:
我感覺mybatis-plus的出現是真的挺nice的,無論是配置還是使用都是那么的令人神往,在配置上與mybatis其實並沒有多大的區別,可能這就是partner吧。它獨有的單表操作,分頁自帶插件,代碼生成器,條件構造器這些強大的功能擴展其實還是很貼合大部分人的口味的。
文章結構:
1. mybatis
2. mybatis-plus
3. 總結
Mybatis:
1.依賴包:
(1)spring:
1 <dependency> 2 <groupId>org.mybatis</groupId> 3 <artifactId>mybatis</artifactId> 4 <version>3.5.2</version> 5 </dependency>
1 <dependency> 2 <groupId>org.mybatis</groupId> 3 <artifactId>mybatis-spring</artifactId> 4 <version>1.3.2</version> 5 </dependency>
(2)spring boot:
1 <dependency> 2 <groupId>org.mybatis.spring.boot</groupId> 3 <artifactId>mybatis-spring-boot-starter</artifactId> 4 <version>2.1.0</version> 5 </dependency>
2.配置:
(1)spring:
- 新建一個mybatis的l配置文件mybatis-config.xml,用於mybatis基本信息的配置:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 8 <!--加載數據庫配置文件--> 9 <properties resource="db.properties"/> 10 11 <!--常用設置--> 12 <settings> 13 <!-- 懶加載。如果設為‘false',則所有相關聯的都會被初始化加載。 --> 14 <setting name="lazyLoadingEnabled" value="true"/> 15 <!-- 當設置為‘true'的時候,懶加載的對象可能被任何懶屬性全部加載。否則,每個屬性都按需加載。 --> 16 <setting name="aggressiveLazyLoading" value="false"/> 17 <!--日志信息打印--> 18 <setting name="logImpl" value="STDOUT_LOGGING"/> 19 <!--緩存設置--> 20 <setting name="cacheEnabled" value="true"/> 21 <!--駝峰命名--> 22 <setting name="mapUnderscoreToCamelCase" value="true"/> 23 </settings> 24 25 <!--別名設置--> 26 <typeAliases> 27 <package name="com.wsw.entity"/> 28 </typeAliases> 29 30 <!--插件配置--> 31 <plugins> 32 <plugin interceptor=""></plugin> 33 </plugins> 34 35 <!--環境配置--> 36 <environments default=""> 37 <environment id=""> 38 <!--事務管理--> 39 <transactionManager type=""> 40 <property name="" value=""/> 41 </transactionManager> 42 <!--數據源配置--> 43 <dataSource type=""> 44 <property name="" value=""/> 45 <property name="" value=""/> 46 </dataSource> 47 </environment> 48 </environments> 49 50 <!--映射文件配置:下面三種方式可隨機采用其中一種--> 51 <mappers> 52 <!--相對路徑文件映射--> 53 <mapper resource=""/> 54 <!--絕對路徑文件映射--> 55 <mapper url=""/> 56 <!--包映射--> 57 <package name=""/> 58 </mappers> 59 60 </configuration>
- 在spring的配置文件applicationContext.xml中配置mybatis的sqlSessionFactory,同時加載mybatis的配置文件:
1 <!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用來產生sqlSessionFactory的 --> 2 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 3 <!-- 加載mybatis的全局配置文件 --> 4 <property name="configLocation" value="classpath:mybatis-config.xml"/> 5 </bean>
(2)spring boot(yaml):
- 在spring boot的全局配置文件application.yaml中配置mybatis相關屬性:
1 mybatis-plus: 2 #別名設置 3 type-aliases-package: com.wsw.springboot.entity 6 #映射文件掃描 7 #mapper-locations: 8 configuration: 9 #懶加載設置 10 lazy-loading-enabled: true 11 #日志打印 12 #log-impl: 13 #駝峰命名 14 map-underscore-to-camel-case: true 15 #緩存設置 16 cache-enabled: true 17 #主鍵自動生成並獲取 18 use-generated-keys: true
3.使用:
實體類:User->School->Page
1 @Data 2 @ToString 3 @AllArgsConstructor 4 @NoArgsConstructor 5 public class User { 6 /** 7 * 用戶編號 8 */ 9 private int uId; 10 /** 11 * 用戶姓名 12 */ 13 private String uName; 14 /** 15 * 用戶性別 16 */ 17 private int uSex; 18 /** 19 * 用戶年齡 20 */ 21 private int uAge; 22 /** 23 * 用戶身份證 24 */ 25 private String uIdentity; 26 /** 27 * 用戶出生日期 28 */ 29 private Timestamp uBirth; 30 /** 31 * 關聯學校:1:1 32 */ 33 private School school; 34 }
1 @AllArgsConstructor 2 @NoArgsConstructor 3 @Data 4 @ToString 5 public class School { 6 /** 7 * 學校編號 8 */ 9 private int schoolId; 10 /** 11 * 學校名稱 12 */ 13 private String schoolName; 14 /** 15 * 學校面積 16 */ 17 private double schoolSize; 18 /** 19 * 一對多 20 */ 21 List<User> userList; 22 }
1 @Data 2 @AllArgsConstructor 3 @NoArgsConstructor 4 @ToString 5 public class Page<T> { 6 7 /** 8 * 當前頁號 9 */ 10 private int pageNo; 11 /** 12 * 當前頁面大小 13 */ 14 private int pageSize; 15 /** 16 * 總記錄數 17 */ 18 private int totalCount; 19 /** 20 * 總頁數 21 */ 22 private int totalPage; 23 /** 24 * 每頁的顯示的數據 25 */ 26 private List<User> lists; 27 28 }
dao層接口:UserDao->SchoolDao
1 @Repository 2 public interface UserDao { 3 4 /** 5 * 查看所有用戶 6 * @return 7 */ 8 List<User> selectAll(); 9 10 /** 11 * 插入一條用戶記錄 12 * @param user 13 */ 14 void insertOne(User user); 15 16 /** 17 * 分頁查詢 18 * @param pageNum:偏移量,代表從第pageNum+1的位置開始取記錄 19 * @param pageCount:取記錄的總數 20 * @return 21 */ 22 List<User> selectByPageNo(@Param("pageNum") int pageNum, @Param("pageCount") int pageCount); 23 24 /** 25 * 查詢所有記錄數 26 * @return 27 */ 28 int selectTotalCount(); 29 30 }
1 @Repository 2 public interface SchoolDao { 3 /** 4 * 查看所有的學校信息 5 * @return 6 */ 7 List<School> selectAllSchool(); 8 9 /** 10 * 模糊查詢-like關鍵字使用 11 * @param sName 12 * @return 13 */ 14 List<School> selectLikeParam(@Param(value = "sName") String sName); 15 16 /** 17 * 條件查詢-if,where等條件使用 18 * @param min 19 * @param max 20 * @return 21 */ 22 List<School> selectInAverage(@Param(value = "min") double min, @Param("max") double max); 23 }
service層:UserService->UserServiceImpl ->SchoolService->SchoolServiceImpl
1 public interface UserService { 2 /** 3 * 查詢所有用戶 4 * @return 5 */ 6 List<User> getAll(); 7 8 /** 9 * 創建一條用戶記錄 10 * @param user 11 */ 12 void createOne(User user); 13 14 /** 15 * 分頁顯示用戶記錄 16 * @param pageNum 17 * @param pageCount 18 * @return 19 */ 20 Page<User> selectByPage(int pageNum, int pageCount); 21 22 }
1 @Service("userService") 2 @Transactional 3 public class UserServiceImpl implements UserService { 4 5 @Autowired 6 private UserDao userDao; 7 8 @Override 9 public List<User> getAll() { 10 return userDao.selectAll(); 11 } 12 13 @Override 14 public void createOne(User user) { 15 userDao.insertOne(user); 16 } 17 18 @Override 19 public Page<User> selectByPage(int pageNum, int pageCount) { 20 Page<User> page = new Page<User>(); 21 //設置總記錄數 22 page.setTotalCount(userDao.selectTotalCount()); 23 //設置每一頁顯示的記錄數 24 page.setPageSize(pageCount); 25 //設置當前總頁數:如果當前的總記錄數能夠整除每一頁的頁面記錄數大小,則總頁數為除后結果 26 if ((page.getTotalCount() - pageNum) % page.getPageSize() == 0) { 27 page.setTotalPage((page.getTotalCount() - pageNum) / page.getPageSize()); 28 } else { 29 //否則為結果加一 30 page.setTotalPage(((page.getTotalCount() - pageNum) / page.getPageSize()) + 1); 31 } 32 //總記錄數小於每頁要求記錄數時默認為1 33 if (page.getTotalCount() < page.getPageSize()) { 34 page.setTotalPage(1); 35 } 36 page.setLists(userDao.selectByPageNo(pageNum, pageCount)); 37 return page; 38 } 39 40 }
1 public interface SchoolService { 2 /** 3 * 查看所有學校記錄 4 * @return 5 */ 6 List<School> getAll(); 7 8 /** 9 * 模糊查詢:like關鍵字使用 10 * @param sName 11 * @return 12 */ 13 List<School> useLike(String sName); 14 15 /** 16 * 條件查詢 17 * @param min 18 * @param max 19 * @return 20 */ 21 List<School> useConditions(double min,double max); 22 }
1 @Service("schoolService") 2 @Transactional 3 public class SchoolServiceImpl implements SchoolService { 4 5 @Autowired 6 private SchoolDao schoolDao; 7 8 @Override 9 public List<School> getAll() { 10 return schoolDao.selectAllSchool(); 11 } 12 13 @Override 14 public List<School> useLike(String sName) { 15 return schoolDao.selectLikeParam(sName); 16 } 17 18 @Override 19 public List<School> useConditions(double min, double max) { 20 return schoolDao.selectInAverage(min, max); 21 } 22 }
映射文件:user-mapper.xml->school-mapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 5 <mapper namespace="com.sunsharing.dao.UserDao"> 6 7 <!--一對一關聯嵌套查詢--> 8 <resultMap id="asossiateWithSchool" type="user"> 9 <id property="uId" column="u_id"/> 10 <result property="uName" column="u_name"/> 11 <result property="uSex" column="u_sex"/> 12 <result property="uAge" column="u_age"/> 13 <result property="uBirth" column="u_birth"/> 14 <association property="school" javaType="school" column="school_id" select="selectSchool"/> 15 </resultMap> 16 17 <select id="selectAll" resultMap="asossiateWithSchool"> 18 select *from `user` 19 </select> 20 21 <select id="selectSchool" resultType="school"> 22 select *from `user` u,school s where u.school_id=s.school_id and u_id=#{uId} 23 </select> 24 <!--插入一條記錄,允許主鍵自增,獲取主鍵--> 25 <insert id="insertOne" parameterType="user" useGeneratedKeys="true"> 26 INSERT INTO `react`.`user` 27 (`u_id`, `u_name`, `u_sex`, `u_age`, `u_identity`, `u_birth`) 28 VALUES 29 (#{uId}, #{uName},#{uSex}, #{uAge}, #{uIdentity}, #{uBirth}) 30 </insert> 31 32 <!--傳入參數包含多個--> 33 <parameterMap id="parameters" type="int"> 34 <parameter property="pageNum" javaType="int"/> 35 <parameter property="pageCount" javaType="int"/> 36 </parameterMap> 37 38 <select id="selectByPageNo" parameterMap="parameters" resultType="user"> 39 select *from `user` limit #{pageNum},#{pageCount} 40 </select> 41 42 <select id="selectTotalCount" resultType="int"> 43 select count(0) from `user` 44 </select> 45 46 </mapper>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 5 <mapper namespace="com.sunsharing.dao.SchoolDao"> 6 7 <!--嵌套查詢,包含多對一的關系--> 8 <resultMap id="assosiateWithUser" type="school"> 9 <id property="schoolId" column="school_id"/> 10 <result property="schoolName" column="school_name"/> 11 <collection property="userList" ofType="user" column="u_id"/> 12 </resultMap> 13 14 <select id="selectAllSchool" resultMap="assosiateWithUser"> 15 select *from school 16 </select> 17 18 <!--like關鍵字使用 :搭配if,where,可多條件累加--> 19 <select id="selectLikeParam" parameterType="java.lang.String" resultType="school"> 20 <bind name="sName" value="'%' + sName + '%'"/> 21 select *from school 22 <where> 23 <!--下面兩種方式可供選擇--> 24 <if test="sName!=null"> 25 <!--1.使用$符號聲明變量可能造成sql注入的威脅--> 26 school_name like '%${sName}%' 27 </if> 28 <if test="sName!=null"> 29 <!--2.通過bind拼湊字符串,防止sql注入--> 30 school_name like #{sName} 31 </if> 32 </where> 33 </select> 34 35 <!--like關鍵字使用 :搭配choose,when,供多條件選擇--> 36 <select id="selectLikeParam" parameterType="java.lang.String" resultType="school"> 37 select *from school 38 <choose> 39 <when test="schoolName!=null"> 40 school_Name like #{sName} 41 </when> 42 <when test="schoolName==null"> 43 school_Name like '清華小學' 44 </when> 45 </choose> 46 </select> 47 48 <parameterMap id="parameters" type="double"> 49 <parameter property="min" javaType="double"/> 50 <parameter property="max" javaType="double"/> 51 </parameterMap> 52 53 <!-- where,if,>,<符號使用--> 54 <select id="selectInAverage" parameterMap="parameters" resultType="school"> 55 select *from school school_size 56 <where> 57 <if test="min!=null || max!=null"> 58 <!--<![CDATA[>]]>表示為>符號--> 59 school_size <![CDATA[>]]> #{min} and school_size <![CDATA[<]]> #{max} 60 </if> 61 62 </where> 63 64 </select> 65 66 </mapper>
單元測試:
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration("classpath:applicationContext.xml") 3 public class BaseTest { 4 }
1 public class UnitTest extends BaseTest { 2 3 @Autowired 4 private UserService userService; 5 6 @Autowired 7 private SchoolService schoolService; 8 9 @Test 10 public void showByPage() { 11 //3為sql查詢limit函數的第一個參數(x),代表從x+1的位置開始執行查詢(默認為0) 12 // 2為限制每次顯示的記錄數,相當於頁面大小 13 Page<User> page = userService.selectByPage(3, 2); 14 List<User> list = page.getLists(); 15 System.out.println("分頁查詢記錄顯示:"); 16 list.stream().forEach(System.out::println); 17 System.out.println("每頁的記錄數為:" + page.getPageSize()); 18 System.out.println("總頁數為:" + page.getTotalPage()); 19 System.out.println("總記錄數:" + page.getTotalCount()); 20 } 21 22 @Test 23 public void showManyToOne() { 24 List<School> schools = schoolService.getAll(); 25 schools.stream().forEach(System.out::println); 26 } 27 28 @Test 29 public void showOneToOne() { 30 List<User> list = userService.getAll(); 31 list.stream().forEach(System.out::println); 32 } 33 34 @Test 35 public void useLike() { 36 List<School> schoolList = schoolService.useLike("清華"); 37 schoolList.stream().forEach(System.out::println); 38 } 39 40 @Test 41 public void useIf() { 42 List<School> list = schoolService.useConditions(500.0, 720.0); 43 list.stream().forEach(System.out::println); 44 } 45 46 }
效果截圖:
showByPage():
showManyToOne():
showOneToOne():
useLike():
useIf():
4.總結:
mybatis:
1.半對象-關系型orm框架,對jdbc的底層數據庫連接,銷毀等封裝性高,對sql語句封裝性較差,可通過手寫sql實現復雜的sql操作。
2.提供一對一,一對多的復雜嵌套查詢機制。
3.可使用動態sql靈活的操作相關sql語句,實現sql的動態變化,功能相對完善。
Mybatis-plus:
在mybatis的基礎上增加了一些新的擴展,比如單表操作以對象操作數據庫,提供mp自帶分頁插件、分頁工具類等,提供許多條件構造器,提供強大的代碼生成器等等。
依賴包:
1 <!--spring boot--> 2 <dependency> 3 <groupId>com.baomidou</groupId> 4 <artifactId>mybatis-plus-boot-starter</artifactId> 5 <version>3.2.0</version> 6 </dependency> 7 8 <!--spring--> 9 <dependency> 10 <groupId>com.baomidou</groupId> 11 <artifactId>mybatis-plus</artifactId> 12 <version>3.2.0</version> 13 </dependency>
1.單表操作面向對象化:
前提:單表,繼承BaseMapper<T>接口
簡單crud:
實體類
1 @Data 2 @ToString 3 @AllArgsConstructor 4 @NoArgsConstructor 5 @TableName(value = "house") 6 public class House { 7 /** 8 * 注意:如果id與數據庫字段對應不上,需要自動配置value與數據庫表中字段關聯 9 */ 10 @TableId(value = "house_id") 11 private Integer houseId; 12 private String houseName; 13 private Double houseArea; 14 private Double housePrice; 15 private Integer uId; 16 }
dao層接口
@Repository public interface HouseDao extends BaseMapper<House> { }
測試
1 @Autowired 2 private HouseDao houseDao; 3 4 @Test 5 public void unitTest() { 6 //create 7 House house = new House(6, "枋湖公園", 500.25, 1000.9, 2); 8 houseDao.insert(house); 9 System.out.println("單條記錄插入成功!"); 10 //read 11 System.out.println("id為6的房子記錄:" + houseDao.selectById(6)); 12 //update 13 house.setHouseName("修改房名"); 14 houseDao.updateById(house); 15 System.out.println("修改后的記錄:" + houseDao.selectById(6)); 16 //delete 17 houseDao.deleteById(6); 18 System.out.println(null == houseDao.selectById(6) ? "記錄已刪除" : "記錄未刪除"); 19 }
效果截圖:
2.分頁:
HouseService->HouseServiceImpl->HouseController
1 /** 2 * 翻頁顯示記錄 3 * @return 4 */ 5 List<House> selectByPage(Integer currPageNo, Integer pageSize);
1 @Override 2 public List<House> selectByPage(Integer currPageNo, Integer pageSize) { 3 // 分頁查詢 pageSize 條用戶id為1的房源記錄 4 List<House> houseList = houseDao.selectPage( 5 new Page<House>(currPageNo, pageSize), 6 new QueryWrapper<House>().eq("u_id", "1") 7 ).getRecords(); 8 return houseList; 9 }
1 @GetMapping("/test/{pageNo}/{pageSize}") 2 public String byPageFromMplus(@PathVariable(name = "pageNo") Integer currPage, @PathVariable(name = "pageSize") Integer pageSize) { 3 List<House> list = houseService.selectByPage(currPage, pageSize); 4 System.out.println("顯示列表:"+list); 5 //循環遍歷 6 list.stream().forEach(System.out::println); 7 return "分頁顯示:"+list; 8 }
效果截圖:
3.條件構造器:
1 /** 2 * 各種條件構造函數的熟悉使用 3 */ 4 @Test 5 public void conditionTest() { 6 //ge(String "column",Object value) :對應的是數據庫的字段名稱 ,ge表示大於等於 7 System.out.println("房子面積大於120的記錄數為:" + houseDao.selectCount(new QueryWrapper<House>().ge("house_area", 120))); 8 //eq(String "column",Object value): eq表示等於 9 System.out.println("房子面積等於120的記錄為:" + houseDao.selectOne(new QueryWrapper<House>().eq("house_area", 120))); 10 House house = new House(); 11 house.setHouseId(1); 12 //set(String "column",Object value):set表示設置當前column的值為value 13 houseDao.update(house, new UpdateWrapper<House>().set("house_name", "測試")); 14 System.out.println("修改后記錄為:" + houseDao.selectById(1)); 15 //between(String "column",Object val1,Object val2): between表示當前的column的值范圍在val1-val2之間 16 List<House> houseList = houseDao.selectList(new QueryWrapper<House>().between("house_area", 120, 160)); 17 System.out.println("房子面積在120-150之間的所有記錄為:"); 18 houseList.stream().forEach(System.out::println); 19 }
效果截圖:
4.強大的代碼生成器:
ps:默認的模板引擎是velocity,如果未聲明
依賴:
1 <dependency> 2 <groupId>com.baomidou</groupId> 3 <artifactId>mybatis-plus-generator</artifactId> 4 <version>3.0.7</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.apache.velocity</groupId> 9 <artifactId>velocity</artifactId> 10 <version>1.7</version> 11 </dependency>
附上筆者自己根據官方文檔整理出來的小小工具類,用於代碼生成。
ps:有些配置還沒怎么搞懂,但大致功能已經實現且能夠成功運行。
1 package com.wsw.springboot.util; 2 3 import com.baomidou.mybatisplus.generator.AutoGenerator; 4 import com.baomidou.mybatisplus.generator.InjectionConfig; 5 import com.baomidou.mybatisplus.generator.config.DataSourceConfig; 6 import com.baomidou.mybatisplus.generator.config.GlobalConfig; 7 import com.baomidou.mybatisplus.generator.config.PackageConfig; 8 import com.baomidou.mybatisplus.generator.config.StrategyConfig; 9 import com.baomidou.mybatisplus.generator.config.TemplateConfig; 10 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; 11 12 13 /** 14 * 工具類:mybatis-plus:代碼生成 15 * @author :wen 16 */ 17 public class GenerateCodeDevUtil { 18 /** 19 * Service接口是否統一I開頭 20 */ 21 private static final boolean SERVICE_BEGIN_WHTH_I = false; 22 /** 23 * 設置包名 24 */ 25 private static final String PACKAGE_NAME = "com.admin"; 26 /** 27 *數據庫驅動名稱 28 */ 29 private static final String DRIVER_NAME = "com.mysql.jdbc.Driver"; 30 /** 31 *數據庫URL 32 */ 33 private static final String URL = "jdbc:mysql://localhost:3306/springboot?characterEncoding=utf8"; 34 /** 35 *數據庫User 36 */ 37 private static final String USER = "root"; 38 /** 39 *數據庫連接密碼 40 */ 41 private static final String PASSWORD = "199815"; 42 43 /** 44 * 私有化構造器:外部無需new對象,直接通過類名調用方法 45 */ 46 private GenerateCodeDevUtil() { 47 48 } 49 50 /** 51 * 全局配置:相當於mybatis-plus.xml進行相關配置 52 * @return 53 */ 54 private static GlobalConfig globalConfig() { 55 GlobalConfig globalConfig = new GlobalConfig(); 56 //作者名 57 globalConfig.setAuthor("wen"); 58 //文件輸出目錄 59 globalConfig.setOutputDir("C:\\Users\\Administrator\\Desktop\\demo"); 60 //根據數據庫列表名稱 61 globalConfig.setBaseColumnList(true); 62 globalConfig.setActiveRecord(true); 63 globalConfig.setBaseResultMap(true); 64 //緩存配置 65 globalConfig.setEnableCache(true); 66 //文件重寫 67 globalConfig.setFileOverride(true); 68 //設置控制層類命名 +%s默認加上實體類名前綴 69 globalConfig.setControllerName("%sController"); 70 //設置dao層接口名稱 71 globalConfig.setMapperName("%sDao"); 72 //設置serviceImpl層類名稱 73 globalConfig.setServiceImplName("%sServiceImpl"); 74 globalConfig.setServiceName("%sService"); 75 return globalConfig; 76 } 77 78 /** 79 * 數據源配置 80 * @return 81 */ 82 private static DataSourceConfig dataSourceConfig() { 83 DataSourceConfig dataSourceConfig = new DataSourceConfig(); 84 dataSourceConfig.setDriverName(DRIVER_NAME); 85 dataSourceConfig.setUrl(URL); 86 dataSourceConfig.setUsername(USER); 87 dataSourceConfig.setPassword(PASSWORD); 88 return dataSourceConfig; 89 } 90 91 /** 92 * 包配置:包括每一層的包命名:controller/entity/dao/service/serviceImpl 93 * @return 94 */ 95 private static PackageConfig packageConfig() { 96 PackageConfig packageConfig = new PackageConfig(); 97 packageConfig.setParent(PACKAGE_NAME); 98 packageConfig.setController("controller"); 99 packageConfig.setEntity("entity"); 100 packageConfig.setMapper("dao"); 101 packageConfig.setService("service"); 102 packageConfig.setServiceImpl("service.impl"); 103 return packageConfig; 104 } 105 106 /** 107 * 自定義配置,包括文件命名,輸出目錄等 108 * @return 109 */ 110 private static InjectionConfig injectionConfig() { 111 InjectionConfig injectionConfig = new InjectionConfig() { 112 @Override 113 public void initMap() { 114 115 } 116 }; 117 return injectionConfig; 118 } 119 120 /** 121 * 模板配置 122 * @return 123 */ 124 private static TemplateConfig templateConfig() { 125 TemplateConfig templateConfig = new TemplateConfig(); 126 //配置生成的xml路徑 127 return templateConfig; 128 } 129 130 /** 131 * 策略配置:命名,前綴,表字段 132 * @return 133 */ 134 private static StrategyConfig strategyConfig() { 135 StrategyConfig strategyConfig = new StrategyConfig(); 136 strategyConfig.setEntityBuilderModel(true); 137 strategyConfig.setVersionFieldName("super code man"); 138 strategyConfig.setCapitalMode(true); 139 //設置數據庫表名 140 strategyConfig.setInclude("users", "house"); 141 //駝峰命名 142 strategyConfig.setNaming(NamingStrategy.underline_to_camel); 143 //實體類不加注解 144 strategyConfig.setEntityTableFieldAnnotationEnable(false); 145 return strategyConfig; 146 } 147 148 /** 149 * 加載全部配置 150 */ 151 public static void start() { 152 AutoGenerator autoGenerator = new AutoGenerator(); 153 autoGenerator.setCfg(injectionConfig()); 154 autoGenerator.setTemplate(templateConfig()); 155 autoGenerator.setPackageInfo(packageConfig()); 156 autoGenerator.setDataSource(dataSourceConfig()); 157 autoGenerator.setGlobalConfig(globalConfig()); 158 autoGenerator.setStrategy(strategyConfig()); 159 System.out.println("全部配置加載成功!開始執行生成代碼..."); 160 autoGenerator.execute(); 161 } 162 163 }
效果截圖:
控制台:
生成文件:
里面的內容也是有自動添加,可能有些配置不怎么清楚,生成的配置有點簡陋。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="com.admin.dao.HouseDao"> 4 5 <!-- 開啟二級緩存 --> 6 <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/> 7 8 <!-- 通用查詢映射結果 --> 9 <resultMap id="BaseResultMap" type="com.admin.entity.House"> 10 <id column="house_id" property="houseId" /> 11 <result column="house_name" property="houseName" /> 12 <result column="house_area" property="houseArea" /> 13 <result column="house_price" property="housePrice" /> 14 <result column="u_id" property="uId" /> 15 </resultMap> 16 17 <!-- 通用查詢結果列 --> 18 <sql id="Base_Column_List"> 19 house_id, house_name, house_area, house_price, u_id 20 </sql> 21 22 </mapper>
package com.admin.service; import com.admin.entity.House; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服務類 * </p> * * @author wen * @since 2019-10-25 */ public interface HouseService extends IService<House> { }
1 package com.admin.dao; 2 3 import com.admin.entity.House; 4 import com.baomidou.mybatisplus.core.mapper.BaseMapper; 5 6 /** 7 * <p> 8 * Mapper 接口 9 * </p> 10 * 11 * @author wen 12 * @since 2019-10-25 13 */ 14 public interface HouseDao extends BaseMapper<House> { 15 16 }
mybatis 與 mybatis-plus的區別:
相同之處:
1.在相關信息配置上mybatis與mybatis-plus的差異性不是很大,基本配置項相同
2.mybatis的多表操作,嵌套查詢與mybatis-plus的操作一致,無差異性
不同之處:
1.mybatis-plus對單表的操作不再依靠書寫sql,dao層映射,而是通過操作對象來實現單表的增刪查改相關操作。
2.mybtis-plus在mybatis的基礎上擴展了許多功能,可以通過mybatis-plus的提供的分頁插件實現分頁,也可以通過mybatis-plus的條件構造實現mybatis單表的動態sql,無需再通過配置文件進行復雜sql的書寫。
3.mybatis的逆向工程插件包mybatis-generator與mybatis-plus的mybatisplus-generator實際使用方式發生改變,mybatis是通過xml配置文件進行逆向工程相關信息的配置,mybatis-plus則是通過提供的配置相關類進行代碼層的配置,並且可以實現個性化配置。