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 ...
随机推荐
- redis-storage介绍[转]
背景: 当时我们正在做一个游戏项目,游戏项目相比于web项目,更追求的是单机的性能,而我们对单个请求的处理时间有着bt级的需求(一个完整的api请求控制在10ms以内).当时我们的数据层用的是ttse ...
- swift - scrollview 判断左右移动, 以及上下两个view联动
核心代码 1. 2. 3. 界面代码VFL /* 浏览作品view*/ import UIKit /** * 图片浏览器(大图和缩略图) */ class JYBrowseWorksView: UIV ...
- thinkphp 查找表并返回结果
使用 M('devices')->where($data)-> execute($resql); 返回的只是int值,表示成功与否,并没有返回search 到的 record . $res ...
- vue内引入jsPlumb流程控制器(一)
1. npm i jsplumb --save 注:jsplumb要全小写 2. 在main.js内 加: import jsPlumb from 'jsplumb' Vue.prototype.$j ...
- 微信小程序 错误记录
1.报错this.getUserInfo(this.setData) is not a function;at pages/index/index onShow function;at api req ...
- Python开发之数据类型
Python数据类型 本节内容 数字 字符串 列表 元祖 字典 列表 集合 一 数字 数字在Python中分为整形,长整型,浮点数,负数等.在Python3中已经不再区分整形和长整形 1 整形 整形是 ...
- python 网络下载的三种风格 未完成
import osimport timeimport sys import requests#依序下载POP20_CC = ('CN IN US ID BR PK NG BD RU JP' 'MX P ...
- UML 图C#
继承关系(类1继承类2) 代码: class Class1:Class2 { } class Class2 { } 实现(实现接口) 代码: interface interface1 { void s ...
- hdu 5129 (枚举) The E-pang Palace
题目;http://acm.hdu.edu.cn/showproblem.php?pid=5128. 给你n个点,问能否组成两个不相交的与坐标轴平行的矩形,能就输出两矩形的面积和,不能就输出一个字符串 ...
- Delphi,C语言互通脚本引擎研究
基于大神akuma的脚本引擎. 下面是demo