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 ...
随机推荐
- Linux 线程】线程同步《四》
1.信号量 (1)概念 信号量和互斥锁(mutex)的区别:互斥锁只允许一个线程进入临界区,而信号量允许多个线程同时进入临界区. 不多做解释,要使用信号量同步,需要包含头文件semaphore.h. ...
- 使用python读写CSV文件
# -*- coding:UTF-8 -*- __autor__ = 'zhouli' __date__ = '2018/10/25 21:14' import csv with open('resu ...
- Android的事件分发机制
public boolean dispatchTouchEvent(MotionEvent event) 通过方法名我们不难猜测,它就是事件分发的重要方法.那么很明显,如果一个MotionEvent传 ...
- 在textarea中鼠标指定的位置插入字符或表情
有些时候我们已经在textarea中输入了一些字符,然后想在鼠标指定的位置插入表情或者字符,这就需要用到jquery的一个小插件了. 代码如下: (function ($) { $.fn.extend ...
- iOS | 使用HBuilder进行云端打包步骤
1.先在HBuilder本地项目中的Manifest.json文件中进行项目配置,将应用的图标和启动图,按照固定的尺寸进行配置.设置应用名称,版本号, 这里的appid不需要修改,是HBuilder自 ...
- 分析params_s方法
/** * 解析启动模式参数 * @param $opt */ static public function params_s($opt) { //判断传入了s参数但是值,则提示错误 if ((iss ...
- tensorflow.reshap(tensor,shape,name)的使用说明
tensorflow as tf tf.reshape(tensor, shape, name=None) reshape作用是将tensor变换为指定shape的形式. 其中shape为一个列表形式 ...
- ssm介绍
1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE ...
- VS2010下MFC的串口编程
串口通信简介 一般来说,计算机都有一个或多个串行端口,这些串口提供了外部设备与PC进行数据传输和通信的通道,在CPU和外设之间充当解释器的角色.当字符数据从CPU发送给外设时,这些字符数据将被转换成串 ...
- ubuntu下安装配置ADB
1.下载SDK Tools for Linux,地址:http://developer.android.com/sdk/index.html 2.解压,将 android-sdk-linux 文件夹放 ...