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