spring整合mybatisplus2.x詳解


一丶Mp的配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
 7     xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
 8         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
10         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
11     
12     
13     <!-- 數據源 -->
14     <context:property-placeholder location="classpath:db.properties"/>
15     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
16         <property name="driverClass" value="${jdbc.driver}"></property>
17         <property name="jdbcUrl" value="${jdbc.url}"></property>
18         <property name="user" value="${jdbc.username}"></property>
19         <property name="password" value="${jdbc.password}"></property>
20     </bean>
21     
22     <!-- 事務管理器 -->
23     <bean id="dataSourceTransactionManager" 
24         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
25         <property name="dataSource" ref="dataSource"></property>
26     </bean>
27     <!-- 基於注解的事務管理 -->
28     <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
29     
30     
31     <!--  配置SqlSessionFactoryBean 
32         Mybatis提供的: org.mybatis.spring.SqlSessionFactoryBean
33         MP提供的:com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
34      -->
35     <bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
36         <!-- 數據源 -->
37         <property name="dataSource" ref="dataSource"></property>
38         <property name="configLocation" value="classpath:mybatis-config.xml"></property>
39         <!-- 別名處理 -->
40         <property name="typeAliasesPackage" value="com.atguigu.mp.beans"></property>    
41         
42         <!-- 注入全局MP策略配置 -->
43         <property name="globalConfig" ref="globalConfiguration"></property>
44     </bean>
45     
46     <!-- 定義MybatisPlus的全局策略配置-->
47     <bean id ="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
48         <!-- 在2.3版本以后,dbColumnUnderline 默認值就是true -->
49         <property name="dbColumnUnderline" value="true"></property>
50         
51         <!-- 全局的主鍵策略 -->
52         <property name="idType" value="0"></property>
53         
54         <!-- 全局的表前綴策略配置 -->
55         <property name="tablePrefix" value="tbl_"></property>
56     </bean>
57 58     <!-- 
59         配置mybatis 掃描mapper接口的路徑
60      -->
61     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
62         <property name="basePackage" value="com.atguigu.mp.mapper"></property>
63     </bean>
64     
65     
66 </beans>

 


二丶CRUD的常用方法

2.1 Insert 方法

 1 /*
 2  * MybatisPlus會默認使用實體類的類名到數據中找對應的表.
 3  * 
 4  */
 5 //<property name="tablePrefix" value="tbl_"></property>
 6 @TableName(value = "tbl_employee")
 7 public class Employee {
 8     /*
 9      * @TableId: value: 指定表中的主鍵列的列名, 如果實體屬性名與列名一致,可以省略不指定. type: 指定主鍵策略.
10      */
11     //<property name="idType" value="0"></property>
12     @TableId(value = "id", type = IdType.AUTO)
13     private Integer id; // int
14     
15     //<property name="dbColumnUnderline" value="true"></property>
16     @TableField(value = "last_name")
17     private String lastName;
18     private String email;
19     private Integer gender;
20     private Integer age;
21    
22     @TableField(exist = false)
23     //當數據庫里面的表沒有這個字段的時候,就不要寫
24     private Double salary;
25 26 }

 

2.1.1 Insert (對象)

 1 @Test
 2     public void testCommonInsert1() {
 3  4         // 初始化Employee對象
 5         Employee employee = new Employee();
 6         employee.setLastName("MP");
 7         employee.setEmail("mp@atguigu.com");
 8         employee.setGender(1);
 9         employee.setAge(22);
10         employee.setSalary(20000.0);
11         // 插入到數據庫
12         // insert方法在插入時, 會根據實體類的每個屬性進行非空判斷,只有非空的屬性對應的字段才會出現到SQL語句中
13         Integer result = employeeMapper.insert(employee);
14 15         System.out.println("result: " + result);
16     }

 

2.1.2 insertAllColumn(對象)

 1  @Test
 2     public void testCommonInsert() {
 3  4         // 初始化Employee對象
 5         Employee employee = new Employee();
 6         employee.setLastName("MP");
 7         employee.setEmail("mp@atguigu.com");
 8         // employee.setGender(1);
 9         // employee.setAge(22);
10         employee.setSalary(20000.0);
11         // insertAllColumn方法在插入時, 不管屬性是否非空, 屬性所對應的字段都會出現到SQL語句中.
12         Integer result = employeeMapper.insertAllColumn(employee);
13         System.out.println("result: " + result);
14     }

 

2.1.3 獲得主鍵

1       // 獲取當前數據在數據庫中的主鍵值
2         Integer key = employee.getId();
3         System.out.println("key:" + key);

 

2.2 Update 方法

2.2.1 updateById(對象)

 1  /**
 2      * 通用 更新操作
 3      */
 4     @Test
 5     public void testCommonUpdate() {
 6         // 初始化修改對象
 7         Employee employee = new Employee();
 8         employee.setId(7);
 9         employee.setLastName("小澤老師");
10         employee.setEmail("xz@sina.com");
11         employee.setGender(0);
12         Integer result = employeeMapper.updateById(employee);
13         System.out.println("result: " + result);
14     }

 

2.2.2 updateAllColumnById(對象)

 1  /**
 2      * 通用 更新操作
 3      */
 4     @Test
 5     public void testCommonUpdate() {
 6         // 初始化修改對象
 7         Employee employee = new Employee();
 8         employee.setId(7);
 9         employee.setLastName("小澤老師");
10         employee.setEmail("xz@sina.com");
11         employee.setGender(0);
12 13         Integer result = employeeMapper.updateAllColumnById(employee);
14         System.out.println("result: " + result);
15     }

 

2.3 Select 方法

2.3.1 selectById

    
1    // 1. 通過id查詢
2         // Employee employee = employeeMapper.selectById(7);
3         // System.out.println(employee);

 

2.3.2 selectOne 

1    // 2. 通過多個列進行查詢 id + lastName
2         // Employee employee = new Employee();
3         // //employee.setId(7);
4         // employee.setLastName("小澤老師");
5         // employee.setGender(0);
6         //
7         // Employee result = employeeMapper.selectOne(employee);
8         // System.out.println("result: " +result );
9         // 這個只能查一條數據,多的時候回報錯

 

2.3.3 selectBatchIds

   
1    // 3. 通過多個id進行查詢 <foreach>
2         // List<Integer> idList = new ArrayList<>();
3         // idList.add(4);
4         // idList.add(5);
5         // idList.add(6);
6         // idList.add(7);
7         // List<Employee> emps = employeeMapper.selectBatchIds(idList);
8         // System.out.println(emps);

2.3.4 selectByMap 

1   // 4. 通過Map封裝條件查詢
2         // Map<String,Object> columnMap = new HashMap<>();
3         // columnMap.put("last_name", "Tom");
4         // columnMap.put("gender", 1);
5         //
6         // List<Employee> emps = employeeMapper.selectByMap(columnMap);
7         // System.out.println(emps);

2.4 Delete 方法

2.4.1 deleteById   

1   // 1 .根據id進行刪除
2         Integer result = employeeMapper.deleteById(13);
3         System.out.println("result: " + result);

 

2.4.2 deleteByMap      

1  // 2. 根據 條件進行刪除
2         // Map<String,Object> columnMap = new HashMap<>();
3         // columnMap.put("last_name", "MP");
4         // columnMap.put("email", "mp@atguigu.com");
5         // Integer result = employeeMapper.deleteByMap(columnMap);
6         // System.out.println("result: " + result );

2.4.3 deleteBatchIds

      
1  // 3. 批量刪除
2         // List<Integer> idList = new ArrayList<>();
3         // idList.add(3);
4         // idList.add(4);
5         // idList.add(5);
6         // Integer result = employeeMapper.deleteBatchIds(idList);
7         // System.out.println("result: " + result );

 

三丶CRUD原理

  • employeeMapper 的本質 org.apache.ibatis.binding.MapperProxy

  • MapperProxy 中 sqlSession –>SqlSessionFactory

SqlSessionFacotry 中 → Configuration→ MappedStatements

每一個 mappedStatement 都表示 Mapper 接口中的一個方法與 Mapper 映射文件

中的一個 SQL。

MP 在啟動就會挨個分析 xxxMapper 中的方法,並且將對應的 SQL 語句處理好,保

存到 configuration 對象中的 mappedStatements 中.

  • SqlSessionFacotry 中 → Configuration→ MappedStatements

每一個 mappedStatement 都表示 Mapper 接口中的一個方法與 Mapper 映射文件

中的一個 SQL。

MP 在啟動就會挨個分析 xxxMapper 中的方法,並且將對應的 SQL 語句處理好,保

存到 configuration 對象中的 mappedStatements 中.

D. 本質:

Configuration: MyBatis 或者 MP 全局配置對象

MappedStatement:一個 MappedStatement 對象對應 Mapper 配置文件中的一個

select/update/insert/delete 節點,主要描述的是一條 SQL 語句

SqlMethod : 枚舉對象 , MP 支持的 SQL 方法

TableInfo: 數據庫表反射信息 ,可以獲取到數據庫表相關的信息

SqlSource: SQL 語句處理對象

MapperBuilderAssistant: 用於緩存、 SQL 參數、查詢方劑結果集處理等.

通過 MapperBuilderAssistant 將每一個 mappedStatement

添加到 configuration 中的 mappedstatements中

四丶條件構造器

查詢方式 說明
setSqlSelect 設置 SELECT 查詢字段
where WHERE 語句,拼接 + WHERE 條件
and AND 語句,拼接 + AND 字段=值
andNew AND 語句,拼接 + AND (字段=值)
or OR 語句,拼接 + OR 字段=值
orNew OR 語句,拼接 + OR (字段=值)
eq 等於=
allEq 基於 map 內容等於=
ne 不等於<>
gt 大於>
ge 大於等於>=
lt 小於<
le 小於等於<=
like 模糊查詢 LIKE
notLike 模糊查詢 NOT LIKE
in IN 查詢
notIn NOT IN 查詢
isNull NULL 值查詢
isNotNull IS NOT NULL
groupBy 分組 GROUP BY
having HAVING 關鍵詞
orderBy 排序 ORDER BY
orderAsc ASC 排序 ORDER BY
orderDesc DESC 排序 ORDER BY
exists EXISTS 條件語句
notExists NOT EXISTS 條件語句
between BETWEEN 條件語句
notBetween NOT BETWEEN 條件語句
addFilter 自由拼接 SQL
last 拼接在最后,例如:last("LIMIT 1")
  • 官方示例

     1 @Test
     2 public void testTSQL11() {
     3     /*
     4      * 實體帶查詢使用方法  輸出看結果
     5      */
     6     EntityWrapper<User> ew = new EntityWrapper<User>();
     7     ew.setEntity(new User(1));
     8     ew.where("user_name={0}", "'zhangsan'").and("id=1")
     9             .orNew("user_status={0}", "0").or("status=1")
    10             .notLike("user_nickname", "notvalue")
    11             .andNew("new=xx").like("hhh", "ddd")
    12             .andNew("pwd=11").isNotNull("n1,n2").isNull("n3")
    13             .groupBy("x1").groupBy("x2,x3")
    14             .having("x1=11").having("x3=433")
    15             .orderBy("dd").orderBy("d1,d2");
    16     System.out.println(ew.getSqlSegment());
    17 }
    18 int buyCount = selectCount(Condition.create()
    19                 .setSqlSelect("sum(quantity)")
    20                 .isNull("order_id")
    21                 .eq("user_id", 1)
    22                 .eq("type", 1)
    23                 .in("status", new Integer[]{0, 1})
    24                 .eq("product_id", 1)
    25                 .between("created_time", startDate, currentDate)
    26                 .eq("weal", 1));

     

  • 自定義的SQL怎么使用

     1 List<User> selectMyPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
     2 <select id="selectMyPage" resultType="User">
     3   SELECT * FROM user 
     4   <where>
     5   ${ew.sqlSegment}
     6   </where>
     7 </select>
     8 /**
     9 10 - 用戶登錄次數
    11 */
    12 @Select("<script>SELECT * FROM z080_user_login <where> ${ew.sqlSegment} </where></script>")
    13 List<UserLogin> findUserLogin(@Param("ew") Wrapper<?> wrapper);
    14 15 /**
    16 17 - 用戶在線時長
    18 */
    19 @Select("<script>SELECT * FROM z080_user_online <where> ${ew.sqlSegment} </where></script>")
    20 List<UserOnline> findUserOnline(@Param("ew") Wrapper<?> wrapper);

常用的用法:

delete、selectCount、selectList、selectMaps、selectObjs、update。。。。

五丶ActiveRecord(活動記錄)

5.1 java類繼承

1 public class Employee extends Model<Employee> {
2     private Integer id; // int
3     private String lastName;
4     private String email;
5     private Integer gender;
6     private Integer age;
7 }

 

5.2繼承BaseMapper

1 public interface EmployeeMapper extends BaseMapper<Employee> {
2     //   Integer  insertEmployee(Employee employee );
3     //   <insert useGeneratedKeys="true" keyProperty="id" > SQL...</insert>
4 }

 

5.3 測試類

 1 /**
 2      * AR 修改操作
 3      */
 4     @Test
 5     public void testARUpdate() {
 6         Employee employee = new Employee();
 7         employee.setId(20);
 8         employee.setLastName("宋老濕");
 9         employee.setEmail("sls@atguigu.com");
10         employee.setGender(1);
11         employee.setAge(36);
12 13         boolean result = employee.updateById();
14         System.out.println("result:" + result);
15 16     }
17 18     /**
19      * AR 插入操作
20      */
21     @Test
22     public void testARInsert() {
23         Employee employee = new Employee();
24         employee.setLastName("宋老師");
25         employee.setEmail("sls@atguigu.com");
26         employee.setGender(1);
27         employee.setAge(35);
28 29         boolean result = employee.insert();
30         System.out.println("result:" + result);
31     }
32 /**
33      * AR 分頁復雜操作
34      */
35     @Test
36     public void testARPage() {
37 38         Employee employee = new Employee();
39 40         Page<Employee> page = employee.selectPage(new Page<>(1, 1),
41                 new EntityWrapper<Employee>().like("last_name", "老"));
42         List<Employee> emps = page.getRecords();
43         System.out.println(emps);
44     }

七丶插件原理

 1 <!-- 插件注冊 -->
 2         <property name="plugins">
 3             <list>
 4                 <!-- 注冊分頁插件 -->
 5             <bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"></bean>
 6                 <!-- 注冊執行分析插件 -->
 7                 <bean class="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor">
 8                     <property name="stopProceed" value="true"></property>
 9                 </bean>
10                 
11                 <!-- 注冊性能分析插件 -->
12                 <bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
13                     <property name="format" value="true"></property>
14                     <!-- <property name="maxTime" value="5"></property> -->
15                 </bean>
16                 
17                 <!-- 注冊樂觀鎖插件 -->
18         <bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor">
19                 </bean>
20             
21             </list>
22             
23         </property>

7.1分頁插件

 1   /**
 2      * 測試分頁插件
 3      */
 4     @Test
 5     public void testPage() {
 6  7         Page<Employee> page = new Page<>(1, 1);
 8  9         List<Employee> emps = employeeMapper.selectPage(page, null);
10         System.out.println(emps);
11 12         System.out.println("===============獲取分頁相關的一些信息======================");
13 14         System.out.println("總條數:" + page.getTotal());
15         System.out.println("當前頁碼: " + page.getCurrent());
16         System.out.println("總頁碼:" + page.getPages());
17         System.out.println("每頁顯示的條數:" + page.getSize());
18         System.out.println("是否有上一頁: " + page.hasPrevious());
19         System.out.println("是否有下一頁: " + page.hasNext());
20 21         // 將查詢的結果封裝到page對象中
22         page.setRecords(emps);
23         List<Employee> records = page.getRecords();
24         System.out.println(records);
25 26     }

 

7.2分析插件

1 /**
2      * 測試SQL執行分析插件,執行全表刪除的會報錯
3      */
4     @Test
5     public void testSQLExplain() {
6 7         employeeMapper.delete(null); // 全表刪除
8     }

 

7.3性能分析插件

 1 /**
 2      * 測試 性能分析插件
 3      */
 4     @Test
 5     public void testPerformance() {
 6         Employee employee = new Employee();
 7         employee.setLastName("瑪利亞老師");
 8         employee.setEmail("mly@sina.com");
 9         employee.setGender("0");
10         employee.setAge(22);
11 12         employeeMapper.insert(employee);
13 14     }

 

7.4 樂觀鎖插件

 1 @Test
 2     public void testOptimisticLocker() {
 3         // 更新操作
 4         Employee employee = new Employee();
 5         employee.setId(15);
 6         employee.setLastName("TomAA");
 7         employee.setEmail("tomAA@sina.com");
 8         employee.setGender("1");
 9         employee.setAge(22);
10         employee.setVersion(3);
11 12         employeeMapper.updateById(employee);
13 14     }
15 16  @Version
17  private Integer version ;

 

7.5概述

1) 插件機制:
Mybatis 通過插件(Interceptor) 可以做到攔截四大對象相關方法的執行,根據需求, 完
成相關數據的動態改變。
Executor
StatementHandler
ParameterHandler
ResultSetHandler
2) 插件原理
四大對象的每個對象在創建時,都會執行 interceptorChain.pluginAll(),會經過每個插
件對象的 plugin()方法,目的是為當前的四大對象創建代理。代理對象就可以攔截到四
大對象相關方法的執行,因為要執行四大對象的方法需要經過代理.
7.2 分頁插件
1) com.baomidou.mybatisplus.plugins.PaginationInterceptor
7.3 執行分析插件
1) com.baomidou.mybatisplus.plugins.SqlExplainInterceptor
2) SQL 執行分析攔截器,只支持 MySQL5.6.3 以上版本
3) 該插件的作用是分析 DELETE UPDATE 語句,防止小白
或者惡意進行 DELETE UPDATE 全表操作
4) 只建議在開發環境中使用,不建議在生產環境使用
5) 在插件的底層 通過 SQL 語句分析命令:Explain 分析當前的 SQL 語句,
根據結果集中的 Extra 列來斷定當前是否全表操作。
7.4 性能分析插件
1) com.baomidou.mybatisplus.plugins.PerformanceInterceptor
2) 性能分析攔截器,用於輸出每條 SQL 語句及其執行時間java 課程系列
3) SQL 性能執行分析,開發環境使用, 超過指定時間,停止運行。有助於發現問題
7.5 樂觀鎖插件
1) com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor
2) 如果想實現如下需求: 當要更新一條記錄的時候,希望這條記錄沒有被別人更新
3) 樂觀鎖的實現原理:
取出記錄時,獲取當前 version 2
更新時,帶上這個 version 2
執行更新時, set version = yourVersion+1 where version = yourVersion
如果 version 不對,就更新失敗
4) @Version 用於注解實體字段,必須要有。
 

 

 

 

 

 

 

 

 

 

 

 

 

八丶其他配置

 1 <!-- 定義自定義注入器 -->
 2     <bean id="mySqlInjector" class="com.atguigu.mp.injector.MySqlInjector"></bean>
 3     
 4     <!-- 邏輯刪除 -->
 5     <bean id="logicSqlInjector" class="com.baomidou.mybatisplus.mapper.LogicSqlInjector"></bean>
 6     
 7     <!-- 公共字段填充 處理器 -->
 8     <bean id="myMetaObjectHandler" class="com.atguigu.mp.metaObjectHandler.MyMetaObjectHandler"> </bean>
 9     
10     <!-- 配置Oracle主鍵Sequence -->
11     <bean id="oracleKeyGenerator" class="com.baomidou.mybatisplus.incrementer.OracleKeyGenerator"></bean>
12 13 <!------------------------------------------------------------------------>
14 15         <!--注入自定義全局操作 
16         <property name="sqlInjector" ref="mySqlInjector"></property>
17         -->
18         <!-- 注入邏輯刪除 -->
19         <property name="sqlInjector" ref="logicSqlInjector"></property>
20         
21         <!-- 注入邏輯刪除全局值 -->
22         <property name="logicDeleteValue" value = "-1"></property>
23         <property name="logicNotDeleteValue" value="1"></property>
24         
25         <!-- 注入公共字段填充處理器 -->
26         <property name="metaObjectHandler" ref="myMetaObjectHandler"></property>
27         
28         <!-- 注入Oracle主鍵Sequence -->
29         <property name="keyGenerator" ref="oracleKeyGenerator"></property>

 

8.1 自定義全局操作

8.1.1 在 Mapper 接口中定義相關的 CRUD 方法

 1 /**
 2  * <p>
 3  *  Mapper 接口
 4  * </p>
 5  *
 6  * @author weiyunhui
 7  * @since 2018-06-21
 8  */
 9 public interface EmployeeMapper extends BaseMapper<Employee> {
10     
11     int  deleteAll();
12 }

 

8.1.2擴展 AutoSqlInjector inject 方法,實現 Mapper 接口中方法要注入的 SQL

 1 public class MySqlInjector  extends AutoSqlInjector{
 2     
 3     /**
 4      * 擴展inject 方法,完成自定義全局操作
 5      */
 6     @Override
 7     public void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class<?>  ,
 8             Class<?> modelClass, TableInfo table) {
 9         //將EmployeeMapper中定義的deleteAll, 處理成對應的MappedStatement對象,加入到configuration對象中。
10         
11         //注入的SQL語句
12         String sql = "delete from " +table.getTableName();
13         //注入的方法名   一定要與EmployeeMapper接口中的方法名一致
14         String method = "deleteAll" ;
15         
16         //構造SqlSource對象
17         SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
18         
19         //構造一個刪除的MappedStatement
20         this.addDeleteMappedStatement(mapperClass, method, sqlSource);
21         
22     }
23 }

 

8.1.3 在 MP 全局策略中,配置 自定義注入器

 <property name="sqlInjector" ref="mySqlInjector"></property>

啟動的時候會把deleteAll添加進去了

8.2 邏輯刪除

1) com.baomidou.mybatisplus.mapper.LogicSqlInjector
2) logicDeleteValue 邏輯刪除全局值
3) logicNotDeleteValue 邏輯未刪除全局值
4) 在 POJO 的邏輯刪除字段 添加 @TableLogic 注解
5) 會在 mp 自帶查詢和更新方法的 sql 后面,追加『邏輯刪除字段』=『LogicNotDeleteValue
默認值』 刪除方法: deleteById()和其他 delete 方法, 底層 SQL 調用的是 update tbl_xxx
set 『邏輯刪除字段』 =『logicDeleteValue 默認值』

 

8.2.1 xml配置

1 <!-- 邏輯刪除 -->
2     <bean id="logicSqlInjector" class="com.baomidou.mybatisplus.mapper.LogicSqlInjector"></bean>
3 <!-- 注入邏輯刪除 -->
4         <property name="sqlInjector" ref="logicSqlInjector"></property>
5 <!-- 注入邏輯刪除全局值 -->
6         <property name="logicDeleteValue" value = "-1"></property>
7         <property name="logicNotDeleteValue" value="1"></property>

 

8.2.2添加注解

1 @TableLogic   // 邏輯刪除屬性
2     private Integer logicFlag ;

 

8.2.3 方法

 1    /**
 2      * 測試邏輯刪除
 3      */
 4     @Test
 5     public void testLogicDelete() {
 6         
 7 //      Integer result = userMapper.deleteById(1);
 8 //      System.out.println("result:" +result );
 9         User user = userMapper.selectById(1);
10         System.out.println(user);
11     }

 

 

 

 

 

 

 

 

8.3公共字段填充

8.3.1繼承類重寫方法

 1 /**
 2  * 自定義公共字段填充處理器
 3  */
 4 public class MyMetaObjectHandler extends MetaObjectHandler {
 5  6     /**
 7      * 插入操作 自動填充
 8      */
 9     @Override
10     public void insertFill(MetaObject metaObject) {
11         // 獲取到需要被填充的字段的值
12         Object fieldValue = getFieldValByName("name", metaObject);
13         if (fieldValue == null) {
14             System.out.println("*******插入操作 滿足填充條件*********");
15             setFieldValByName("name", "weiyunhui", metaObject);
16         }
17 18     }
19 20     /**
21      * 修改操作 自動填充
22      */
23     @Override
24     public void updateFill(MetaObject metaObject) {
25         Object fieldValue = getFieldValByName("name", metaObject);
26         if (fieldValue == null) {
27             System.out.println("*******修改操作 滿足填充條件*********");
28             setFieldValByName("name", "weiyh", metaObject);
29         }
30     }
31 32 }

 

8.3.2注解填充字段 @TableFile(fill = FieldFill.INSERT) 查看 FieldFill

@TableField(fill=FieldFill.INSERT_UPDATE)
    private String name ;

 

8.3.3 MP 全局注入 自定義公共字段填充處理器

 1 <!-- 注入公共字段填充處理器 -->
 2         <property name="metaObjectHandler" ref="myMetaObjectHandler"></property>
 3 測試方法
 4 
 5     /**
 6      * 測試公共字段填充
 7      */
 8     @Test
 9     public void testMetaObjectHandler() {
10         User user = new User();
11         //user.setName("Tom");
12         
13         user.setId(5);
14         user.setLogicFlag(1);
15         
16         userMapper.updateById(user);
17     }

 

8.4Oracle序列

8.4.1實體類配置主鍵 Sequence @KeySequence

1 //@KeySequence(value="seq_user",clazz=Integer.class)
2 public class User extends Parent {
3     //@TableId(type=IdType.INPUT)
4     private Integer id  ;

 

8.4.2 全局 MP 主鍵生成策略為 IdType.INPUT

   <!-- Oracle全局主鍵策略 -->
    <property name="idType" value="1"></property>

 

8.4.3全局 MP 中配置 Oracle 主鍵 Sequence

<!-- 注入Oracle主鍵Sequence -->
<property name="keyGenerator" ref="oracleKeyGenerator"></property>

 

8.4.4 寫一個父類

1 @KeySequence(value="seq_user",clazz=Integer.class)
2 public abstract class Parent {
3 4 }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM