Mybatis-Plus 实战完整学习笔记(三)------导入MybatisPlus环境
1。dao层接口引入
package com.baidu.www.mplus.mapper; import com.baidu.www.mplus.bean.Employee;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; /**
* @author liuyangos8888
* <p>
* 抽象接口继承B
* 实际的实现都在
* r
*/
public interface EmployeeMapper extends BaseMapper<Employee> { }
这里主要是继承MybatisPlus 的BaseMapper抽象类,实现其内部拥有的通用的CRUD(增删改查),不用写xml文档,自动实现环境配置
源码
/*
* Copyright (c) 2011-2020, hubin (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.core.mapper; import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map; import org.apache.ibatis.annotations.Param; import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants; /* :`
.:,
:::,,.
:: `::::::
::` `,:,` .:`
`:: `::::::::.:` `:';,`
::::, .:::` `@++++++++:
`` :::` @+++++++++++#
:::, #++++++++++++++`
,: `::::::;'##++++++++++
.@#@;` ::::::::::::::::::::;
#@####@, :::::::::::::::+#;::.
@@######+@:::::::::::::. #@:;
, @@########':::::::::::: .#''':`
;##@@@+:##########@::::::::::: @#;.,:.
#@@@######++++#####'::::::::: .##+,:#`
@@@@@#####+++++'#####+::::::::` ,`::@#:`
`@@@@#####++++++'#####+#':::::::::::@.
@@@@######+++++''#######+##';::::;':,`
@@@@#####+++++'''#######++++++++++`
#@@#####++++++''########++++++++'
`#@######+++++''+########+++++++;
`@@#####+++++''##########++++++,
@@######+++++'##########+++++#`
@@@@#####+++++############++++;
;#@@@@@####++++##############+++,
@@@@@@@@@@@###@###############++'
@#@@@@@@@@@@@@###################+:
`@#@@@@@@@@@@@@@@###################'`
:@#@@@@@@@@@@@@@@@@@##################,
,@@@@@@@@@@@@@@@@@@@@################;
,#@@@@@@@@@@@@@@@@@@@##############+`
.#@@@@@@@@@@@@@@@@@@#############@,
@@@@@@@@@@@@@@@@@@@###########@,
:#@@@@@@@@@@@@@@@@##########@,
`##@@@@@@@@@@@@@@@########+,
`+@@@@@@@@@@@@@@@#####@:`
`:@@@@@@@@@@@@@@##@;.
`,'@@@@##@@@+;,`
``...`` _ _ /_ _ _/_. ____ / _
/ / //_//_//_|/ /_\ /_///_/_\ Talk is cheap. Show me the code.
_/ /
*/ /**
* <p>
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* </p>
* <p>
* 这个 Mapper 支持 id 泛型
* </p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> { /**
* <p>
* 插入一条记录
* </p>
*
* @param entity 实体对象
*/
int insert(T entity); /**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
*/
int deleteById(Serializable id); /**
* <p>
* 根据 columnMap 条件,删除记录
* </p>
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /**
* <p>
* 根据 entity 条件,删除记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 删除(根据ID 批量删除)
* </p>
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /**
* <p>
* 根据 ID 修改
* </p>
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity); /**
* <p>
* 根据 whereEntity 条件,更新记录
* </p>
*
* @param entity 实体对象 (set 条件值,不能为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper); /**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
*/
T selectById(Serializable id); /**
* <p>
* 查询(根据ID 批量查询)
* </p>
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList); /**
* <p>
* 查询(根据 columnMap 条件)
* </p>
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap); /**
* <p>
* 根据 entity 条件,查询一条记录
* </p>
*
* @param queryWrapper 实体对象
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 根据 Wrapper 条件,查询总记录数
* </p>
*
* @param queryWrapper 实体对象
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 根据 entity 条件,查询全部记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 根据 Wrapper 条件,查询全部记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 根据 Wrapper 条件,查询全部记录
* 注意: 只返回第一个字段的值
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 根据 entity 条件,查询全部记录(并翻页)
* </p>
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /**
* <p>
* 根据 Wrapper 条件,查询全部记录(并翻页)
* </p>
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
多数方法都是以命名为其真诚的语句使用方式,所以可以直接调用,很多大企业,也是做了自己企业的类似封装。所以学会这套框架,就是你学会了大企业接口调用的方式。
2.测试类编写
(1)环境测试,测试配置文件是否有效,环境是否搭建成功
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException; /**
* test
*/
public class TestMp {
private ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test
public void context() throws SQLException { DataSource ds = iocContext.getBean("dataSource", DataSource.class);
Connection conn = ds.getConnection();
System.out.println(conn); }
}
(2)CRUD调用测试
import com.baidu.www.mplus.bean.Employee;
import com.baidu.www.mplus.mapper.EmployeeMapper;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.sql.SQLException;
import java.util.List; /**
* test
*/
public class TestCRUD { private ApplicationContext iocContext = new ClassPathXmlApplicationContext("applicationContext.xml"); private EmployeeMapper employeeMapper = iocContext.getBean("employeeMapper",EmployeeMapper.class); private final static Logger logger = Logger.getLogger(TestCRUD.class); Gson gson = new Gson(); /**
* 所有员工列表
*
* @throws SQLException
*/
@Test
public void list() throws SQLException { List<Employee> employeeList = employeeMapper.selectList(null); if (!employeeList.isEmpty()) {
logger.info("所有员工:"+gson.toJson(employeeList));
}
} /**
* 添加用户
* @throws SQLException
*/
@Test
public void add() throws SQLException { Employee employee = new Employee(); employee.setLastName("Betty");
employee.setAge(12);
employee.setEmail("betty@163.com");
employee.setGender(1); Integer result = employeeMapper.insert(employee); if (result!=null||result>0) {
logger.info("+++++++++++++++++添加成功+++++");
}
} /**
* 修改用户
* @throws SQLException
*/
@Test
public void update() throws SQLException { Employee employee = new Employee(); employee.setLastName("Marry");
employee.setAge(12);
employee.setEmail("marry@163.com");
employee.setGender(1); Integer result = employeeMapper.updateById(employee); if (result!=null||result>0) {
logger.info("++++++++++++++++修改成功+++++");
}
} @Test
public void selectById() throws SQLException { Employee employee = employeeMapper.selectById(1); if (employee!=null) {
logger.info("++一个员工信息+++++"+gson.toJson(employee));
}
} }
注意:
CRUD测试,导入了相关jar包,为了显示方便
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
3.可能遇到两个问题,就是数据库名称和实体类对应字段名称不匹配问题
需要修改加入注解@TableName(value = "tbl_employee")和字段@TableField(value = "last_name"),源码如下,同时添加了自动生产ID功能@TableId(type = IdType.AUTO)
源码
package com.baidu.www.mplus.bean; import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName; /**
*
* @author liuyangos8888
*
* 实体类
* 建议使用封装类型String,Integer,方便框架判空
*
*/
@TableName(value = "tbl_employee")
public class Employee{ /**
* 字段的ID
*/
@TableId(type = IdType.AUTO)
private Integer id ; /**
* 名字
*/
@TableField(value = "last_name")
private String lastName; /**
* 邮箱
*/
private String email ; /**
* 性别
*/
private Integer gender ; /**
* 年龄
*/
private Integer age ; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Integer getGender() {
return gender;
} public void setGender(Integer gender) {
this.gender = gender;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
", age=" + age +
'}';
}
}
Mybatis-Plus 实战完整学习笔记(三)------导入MybatisPlus环境的更多相关文章
- Mybatis-Plus 实战完整学习笔记(一)------简介
第一章 简介 1. 什么是MybatisPlus MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只 ...
- 《从Lucene到Elasticsearch:全文检索实战》学习笔记三
今天我给大家讲讲倒排索引. 索引是构成搜索引擎的核心技术之一,它在日常生活中是非常常见的,比如我看一本书的时候,我首先会看书的目录,通过目录可以快速定位到具体章节的页码,加快对内容的查询速度. 文档通 ...
- Mybatis-Plus 实战完整学习笔记(四)------全局参数配置
一.全局配置设置 (1)全局配置Id自动生成 <!--定义mybatisplus全局配置--> <bean id="globalConfig" class=&qu ...
- Mybatis-Plus 实战完整学习笔记(二)------环境搭建
第二章 使用实例 1.搭建测试数据库 -- 创建库 CREATE DATABASE mp; -- 使用库 USE mp; -- 创建表 CREATE TABLE tbl_employee( ...
- Mybatis-Plus 实战完整学习笔记(十一)------条件构造器删除,修改,conditon
1.修改功能--其他过滤方式跟select一样 /** * 修改条件构造器 * @throws SQLException */ @Test public void selectUpdate() thr ...
- Mybatis-Plus 实战完整学习笔记(十)------条件构造器核心用法大全(下)
31.升序orderByAsc 31.升序orderByAsc List<Employee> employeeList = employeeMapper.selectList(new Qu ...
- Mybatis-Plus 实战完整学习笔记(九)------条件构造器核心用法大全(上)
一.Mybatisplus通用(公共方法)CRUD,一共17种(3.0.3版),2.3系列也是这么多,这个新版本一定程度进行了改造和删减. 二.构造器UML图(3.0.3)-----实体包装器,主要用 ...
- Mybatis-Plus 实战完整学习笔记(八)------delete测试
1.根据ID删除一个员工deleteById /** * 删除客户 * * @throws SQLException */ @Test public void deletedMethod() thro ...
- Mybatis-Plus 实战完整学习笔记(七)------select测试二
1.查询selectOne (3.0.3版) @Test public void selectMethod() throws SQLException { // 根据ID获取一个对象的数据 Empl ...
随机推荐
- C语言常用标准库函数
数学函数: 在math.h中 abs(x) :求整型数x的绝对值 cos(x):x(弧度)的余弦 fabs(x):求浮点数x的绝对值 ceil(x):求不小于x的最小整数 floor(x):求不大于x ...
- 有关https有的网站可以访问有的访问不了的问题
在开发中遇到这种情况,在开发工具里面访问可以,当时到了手机上之后就发现有的请求可以正常获取数据,有的则不行. 都是使用https地址,也配置后台了,但是就是不出数据,总是无法请求服务. 后来检查在手机 ...
- mysql left join 多条记录 1:n 的处理方法
一.准备两张表,文章表和评伦表 CREATE TABLE `article` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', ...
- 使用PHP来简单的创建一个RPC服务
RPC全称为Remote Procedure Call,翻译过来为"远程过程调用".主要应用于不同的系统之间的远程通信和相互调用. 比如有两个系统,一个是PHP写的,一个是JAVA ...
- 递归函数 day17
一 递归函数 n = 1 金老板 38+2 =40n = 2 alex n+2= 金老板 36+2 = 38n = 3 wusir n+2 = alex wusir 36 def age(n): #n ...
- 5.Mysql常用函数
5.常用函数函数可以进行字符串的处理.数值计算和日期计算等,mysql可以用在SQL(DML)中以增加SQL的功能.5.1 数值函数1. abs(x) 返回x的绝对值select abs(5),abs ...
- istio promethus收集不到数据
1.重新apply istio.yaml kubectl apply -f install/kubernetes/istio.yaml kubectl get metrics.config.istio ...
- sql server 查询不为空的字段
经常用,经常忘 select * from table where content is not null and datalength(content)<>0
- Atom打开txt文件中文乱码解决、指定文件的语法格式、win10中禁止睡眠
1.Atom中文乱码解决 首先保证打开的txt文件的编码格式为UTF-8无BOM编码格式,可以使用Notepad++更改,如下图所示: 然后再在atom中打开文件,并右键点击文件内容的任意位置,Cha ...
- js 闭包 弊端
闭包有许多有趣的用途,Javascript的两个特征使它这么有趣:1. function是一个对象,它跟数组,Object一样,地位平等.2. Javascript变量作用域范围.<Javasc ...