Mybatis-Plus 實戰完整學習筆記(三)------導入MybatisPlus環境


1。dao層接口引入

 1 package com.baidu.www.mplus.mapper;
 2 
 3 import com.baidu.www.mplus.bean.Employee;
 4 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 5 
 6 /**
 7  * @author liuyangos8888
 8  * <p>
 9  * 抽象接口繼承B
10  *    實際的實現都在
11  *    r
12  */
13 public interface EmployeeMapper extends BaseMapper<Employee> {
14 
15 }
View Code

這里主要是繼承MybatisPlus 的BaseMapper抽象類,實現其內部擁有的通用的CRUD(增刪改查),不用寫xml文檔,自動實現環境配置

源碼

  1 /*
  2  * Copyright (c) 2011-2020, hubin (jobob@qq.com).
  3  * <p>
  4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5  * use this file except in compliance with the License. You may obtain a copy of
  6  * the License at
  7  * <p>
  8  * http://www.apache.org/licenses/LICENSE-2.0
  9  * <p>
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 12  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13  * License for the specific language governing permissions and limitations under
 14  * the License.
 15  */
 16 package com.baomidou.mybatisplus.core.mapper;
 17 
 18 import java.io.Serializable;
 19 import java.util.Collection;
 20 import java.util.List;
 21 import java.util.Map;
 22 
 23 import org.apache.ibatis.annotations.Param;
 24 
 25 import com.baomidou.mybatisplus.core.conditions.Wrapper;
 26 import com.baomidou.mybatisplus.core.metadata.IPage;
 27 import com.baomidou.mybatisplus.core.toolkit.Constants;
 28 
 29 /*
 30 
 31                :`
 32                     .:,
 33                      :::,,.
 34              ::      `::::::
 35              ::`    `,:,` .:`
 36              `:: `::::::::.:`      `:';,`
 37               ::::,     .:::`   `@++++++++:
 38                ``        :::`  @+++++++++++#
 39                          :::, #++++++++++++++`
 40                  ,:      `::::::;'##++++++++++
 41                  .@#@;`   ::::::::::::::::::::;
 42                   #@####@, :::::::::::::::+#;::.
 43                   @@######+@:::::::::::::.  #@:;
 44            ,      @@########':::::::::::: .#''':`
 45            ;##@@@+:##########@::::::::::: @#;.,:.
 46             #@@@######++++#####'::::::::: .##+,:#`
 47             @@@@@#####+++++'#####+::::::::` ,`::@#:`
 48             `@@@@#####++++++'#####+#':::::::::::@.
 49              @@@@######+++++''#######+##';::::;':,`
 50               @@@@#####+++++'''#######++++++++++`
 51                #@@#####++++++''########++++++++'
 52                `#@######+++++''+########+++++++;
 53                 `@@#####+++++''##########++++++,
 54                  @@######+++++'##########+++++#`
 55                 @@@@#####+++++############++++;
 56               ;#@@@@@####++++##############+++,
 57              @@@@@@@@@@@###@###############++'
 58            @#@@@@@@@@@@@@###################+:
 59         `@#@@@@@@@@@@@@@@###################'`
 60       :@#@@@@@@@@@@@@@@@@@##################,
 61       ,@@@@@@@@@@@@@@@@@@@@################;
 62        ,#@@@@@@@@@@@@@@@@@@@##############+`
 63         .#@@@@@@@@@@@@@@@@@@#############@,
 64           @@@@@@@@@@@@@@@@@@@###########@,
 65            :#@@@@@@@@@@@@@@@@##########@,
 66             `##@@@@@@@@@@@@@@@########+,
 67               `+@@@@@@@@@@@@@@@#####@:`
 68                 `:@@@@@@@@@@@@@@##@;.
 69                    `,'@@@@##@@@+;,`
 70                         ``...``
 71 
 72  _ _     /_ _ _/_. ____  /    _
 73 / / //_//_//_|/ /_\  /_///_/_\      Talk is cheap. Show me the code.
 74      _/             /
 75  */
 76 
 77 /**
 78  * <p>
 79  * Mapper 繼承該接口后,無需編寫 mapper.xml 文件,即可獲得CRUD功能
 80  * </p>
 81  * <p>
 82  * 這個 Mapper 支持 id 泛型
 83  * </p>
 84  *
 85  * @author hubin
 86  * @since 2016-01-23
 87  */
 88 public interface BaseMapper<T> {
 89 
 90     /**
 91      * <p>
 92      * 插入一條記錄
 93      * </p>
 94      *
 95      * @param entity 實體對象
 96      */
 97     int insert(T entity);
 98 
 99     /**
100      * <p>
101      * 根據 ID 刪除
102      * </p>
103      *
104      * @param id 主鍵ID
105      */
106     int deleteById(Serializable id);
107 
108     /**
109      * <p>
110      * 根據 columnMap 條件,刪除記錄
111      * </p>
112      *
113      * @param columnMap 表字段 map 對象
114      */
115     int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
116 
117     /**
118      * <p>
119      * 根據 entity 條件,刪除記錄
120      * </p>
121      *
122      * @param queryWrapper 實體對象封裝操作類(可以為 null)
123      */
124     int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
125 
126     /**
127      * <p>
128      * 刪除(根據ID 批量刪除)
129      * </p>
130      *
131      * @param idList 主鍵ID列表(不能為 null 以及 empty)
132      */
133     int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
134 
135     /**
136      * <p>
137      * 根據 ID 修改
138      * </p>
139      *
140      * @param entity 實體對象
141      */
142     int updateById(@Param(Constants.ENTITY) T entity);
143 
144     /**
145      * <p>
146      * 根據 whereEntity 條件,更新記錄
147      * </p>
148      *
149      * @param entity        實體對象 (set 條件值,不能為 null)
150      * @param updateWrapper 實體對象封裝操作類(可以為 null,里面的 entity 用於生成 where 語句)
151      */
152     int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
153 
154     /**
155      * <p>
156      * 根據 ID 查詢
157      * </p>
158      *
159      * @param id 主鍵ID
160      */
161     T selectById(Serializable id);
162 
163     /**
164      * <p>
165      * 查詢(根據ID 批量查詢)
166      * </p>
167      *
168      * @param idList 主鍵ID列表(不能為 null 以及 empty)
169      */
170     List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
171 
172     /**
173      * <p>
174      * 查詢(根據 columnMap 條件)
175      * </p>
176      *
177      * @param columnMap 表字段 map 對象
178      */
179     List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
180 
181     /**
182      * <p>
183      * 根據 entity 條件,查詢一條記錄
184      * </p>
185      *
186      * @param queryWrapper 實體對象
187      */
188     T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
189 
190     /**
191      * <p>
192      * 根據 Wrapper 條件,查詢總記錄數
193      * </p>
194      *
195      * @param queryWrapper 實體對象
196      */
197     Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
198 
199     /**
200      * <p>
201      * 根據 entity 條件,查詢全部記錄
202      * </p>
203      *
204      * @param queryWrapper 實體對象封裝操作類(可以為 null)
205      */
206     List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
207 
208     /**
209      * <p>
210      * 根據 Wrapper 條件,查詢全部記錄
211      * </p>
212      *
213      * @param queryWrapper 實體對象封裝操作類(可以為 null)
214      */
215     List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
216 
217     /**
218      * <p>
219      * 根據 Wrapper 條件,查詢全部記錄
220      * 注意: 只返回第一個字段的值
221      * </p>
222      *
223      * @param queryWrapper 實體對象封裝操作類(可以為 null)
224      */
225     List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
226 
227     /**
228      * <p>
229      * 根據 entity 條件,查詢全部記錄(並翻頁)
230      * </p>
231      *
232      * @param page         分頁查詢條件(可以為 RowBounds.DEFAULT)
233      * @param queryWrapper 實體對象封裝操作類(可以為 null)
234      */
235     IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
236 
237     /**
238      * <p>
239      * 根據 Wrapper 條件,查詢全部記錄(並翻頁)
240      * </p>
241      *
242      * @param page         分頁查詢條件
243      * @param queryWrapper 實體對象封裝操作類
244      */
245     IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
246 }
View Code

多數方法都是以命名為其真誠的語句使用方式,所以可以直接調用,很多大企業,也是做了自己企業的類似封裝。所以學會這套框架,就是你學會了大企業接口調用的方式。

2.測試類編寫

 (1)環境測試,測試配置文件是否有效,環境是否搭建成功

 1 import org.junit.Test;
 2 import org.springframework.context.ApplicationContext;
 3 import org.springframework.context.support.ClassPathXmlApplicationContext;
 4 
 5 
 6 import javax.sql.DataSource;
 7 import java.sql.Connection;
 8 import java.sql.SQLException;
 9 
10 
11 /**
12  * test
13  */
14 public class TestMp {
15     private ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationContext.xml");
16 
17 
18     @Test
19     public void context() throws SQLException {
20 
21         DataSource ds = iocContext.getBean("dataSource", DataSource.class);
22         Connection conn = ds.getConnection();
23         System.out.println(conn);
24 
25     }
26 }
View Code

 (2)CRUD調用測試

  1 import com.baidu.www.mplus.bean.Employee;
  2 import com.baidu.www.mplus.mapper.EmployeeMapper;
  3 import com.google.gson.Gson;
  4 import org.apache.log4j.Logger;
  5 import org.apache.log4j.spi.LoggerFactory;
  6 import org.junit.Test;
  7 import org.springframework.beans.factory.annotation.Autowired;
  8 import org.springframework.context.ApplicationContext;
  9 import org.springframework.context.support.ClassPathXmlApplicationContext;
 10 
 11 import java.sql.SQLException;
 12 import java.util.List;
 13 
 14 
 15 /**
 16  * test
 17  */
 18 public class TestCRUD {
 19 
 20 
 21     private ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationContext.xml");
 22 
 23     private EmployeeMapper employeeMapper = iocContext.getBean("employeeMapper",EmployeeMapper.class);
 24 
 25     private final static Logger logger = Logger.getLogger(TestCRUD.class);
 26 
 27     Gson gson = new Gson();
 28 
 29     /**
 30      * 所有員工列表
 31      *
 32      * @throws SQLException
 33      */
 34     @Test
 35     public void list() throws SQLException {
 36 
 37         List<Employee> employeeList = employeeMapper.selectList(null);
 38 
 39         if (!employeeList.isEmpty()) {
 40             logger.info("所有員工:"+gson.toJson(employeeList));
 41         }
 42     }
 43 
 44     /**
 45      * 添加用戶
 46      * @throws SQLException
 47      */
 48     @Test
 49     public void add() throws SQLException {
 50 
 51         Employee employee = new Employee();
 52 
 53         employee.setLastName("Betty");
 54         employee.setAge(12);
 55         employee.setEmail("betty@163.com");
 56         employee.setGender(1);
 57 
 58         Integer result = employeeMapper.insert(employee);
 59 
 60 
 61         if (result!=null||result>0) {
 62             logger.info("+++++++++++++++++添加成功+++++");
 63         }
 64     }
 65 
 66 
 67     /**
 68      * 修改用戶
 69      * @throws SQLException
 70      */
 71     @Test
 72     public void update() throws SQLException {
 73 
 74         Employee employee = new Employee();
 75 
 76         employee.setLastName("Marry");
 77         employee.setAge(12);
 78         employee.setEmail("marry@163.com");
 79         employee.setGender(1);
 80 
 81         Integer result = employeeMapper.updateById(employee);
 82 
 83 
 84         if (result!=null||result>0) {
 85             logger.info("++++++++++++++++修改成功+++++");
 86         }
 87     }
 88 
 89     @Test
 90     public void selectById() throws SQLException {
 91 
 92         Employee employee = employeeMapper.selectById(1);
 93 
 94 
 95         if (employee!=null) {
 96             logger.info("++一個員工信息+++++"+gson.toJson(employee));
 97         }
 98     }
 99 
100 
101 
102 }
View Code

注意:

    CRUD測試,導入了相關jar包,為了顯示方便

1         <dependency>
2             <groupId>com.google.code.gson</groupId>
3             <artifactId>gson</artifactId>
4             <version>2.3.1</version>
5         </dependency>
View Code

 3.可能遇到兩個問題,就是數據庫名稱和實體類對應字段名稱不匹配問題

需要修改加入注解@TableName(value = "tbl_employee")和字段@TableField(value = "last_name"),源碼如下,同時添加了自動生產ID功能@TableId(type = IdType.AUTO)

源碼

 1 package com.baidu.www.mplus.bean;
 2 
 3 import com.baomidou.mybatisplus.annotation.IdType;
 4 import com.baomidou.mybatisplus.annotation.TableField;
 5 import com.baomidou.mybatisplus.annotation.TableId;
 6 import com.baomidou.mybatisplus.annotation.TableName;
 7 
 8 /**
 9  *
10  * @author liuyangos8888
11  *
12  * 實體類
13  * 建議使用封裝類型String,Integer,方便框架判空
14  *
15  */
16 @TableName(value = "tbl_employee")
17 public class Employee{
18 
19     /**
20      * 字段的ID
21      */
22     @TableId(type = IdType.AUTO)
23     private Integer id ;
24 
25     /**
26      * 名字
27      */
28     @TableField(value = "last_name")
29     private String lastName;
30 
31     /**
32      * 郵箱
33      */
34     private String email ;
35 
36     /**
37      * 性別
38      */
39     private Integer gender ;
40 
41     /**
42      * 年齡
43      */
44     private Integer age ;
45 
46 
47     public Integer getId() {
48         return id;
49     }
50 
51     public void setId(Integer id) {
52         this.id = id;
53     }
54 
55     public String getLastName() {
56         return lastName;
57     }
58 
59     public void setLastName(String lastName) {
60         this.lastName = lastName;
61     }
62 
63     public String getEmail() {
64         return email;
65     }
66 
67     public void setEmail(String email) {
68         this.email = email;
69     }
70 
71     public Integer getGender() {
72         return gender;
73     }
74 
75     public void setGender(Integer gender) {
76         this.gender = gender;
77     }
78 
79     public Integer getAge() {
80         return age;
81     }
82 
83     public void setAge(Integer age) {
84         this.age = age;
85     }
86 
87 
88     @Override
89     public String toString() {
90         return "Employee{" +
91                 "id=" + id +
92                 ", lastName='" + lastName + '\'' +
93                 ", email='" + email + '\'' +
94                 ", gender=" + gender +
95                 ", age=" + age +
96                 '}';
97     }
98 }
View Code

 


免責聲明!

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



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