Mybatis-Plus学习笔记

Posted 江州益彤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis-Plus学习笔记相关的知识,希望对你有一定的参考价值。

一、MyBatis-Plus简介

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

MyBatis-Plus 3.x 文档手册

二、前置知识

Mybatis
Spring
Maven

三、继承mp

3.1、创建测试数据库和需要的数据表



3.2、创建JavaBean

3.3、依赖添加pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.atguigu.mp</groupId>
  <artifactId>mp01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  	<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
	<dependency>
	    <groupId>com.baomidou</groupId>
	    <artifactId>mybatis-plus-boot-starter</artifactId>
	    <version>3.4.2</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/junit/junit -->
	<dependency>
	    <groupId>junit</groupId>
	    <artifactId>junit</artifactId>
	    <version>4.12</version>
	    <scope>test</scope>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/log4j/log4j -->
	<dependency>
	    <groupId>log4j</groupId>
	    <artifactId>log4j</artifactId>
	    <version>1.2.17</version>
	</dependency>
	
  	<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
	<dependency>
	    <groupId>com.mchange</groupId>
	    <artifactId>c3p0</artifactId>
	    <version>0.9.5.2</version>
	</dependency>
  	
  	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>8.0.26</version>
	</dependency>
  	
  	<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>5.3.6</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-orm</artifactId>
	    <version>5.3.14</version>
	</dependency>
  </dependencies>
  
</project>

3.4、依赖配置


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

	<!-- 配置数据源 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 读取数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="$jdbc.driver"></property>
		<property name="jdbcUrl" value="$jdbc.url"></property>
		<property name="user" value="$jdbc.username"></property>
		<property name="password" value="$jdbc.password"></property>
	</bean>
	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入数据源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<!-- 开启事务注解 -->
	<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
	
	<!-- spring整合Mybatis -->
	<!-- 1、Mybatis的sqlsession的创建 -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean" >
		<!-- Mybatis的全局配置文件 -->
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 别名处理 -->
		<property name="typeAliasesPackage" value="com.atguigu.mp.beans"></property>
	</bean>
	
	<!-- Mybatis扫描mapper接口的路径 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.atguigu.mp.mapper"></property>
	</bean>
	
</beans>

db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mp?serverTimezone=Hongkong
jdbc.username=root
jdbc.password=75688

log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %dMM-dd HH:mm:ss,SSS %m  (%F:%L) \\n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 
<configuration>
	
</configuration>

3.5、测试

package com.atguigu.mp.test;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMP 

	private ApplicationContext ios = new ClassPathXmlApplicationContext("applicationContext.xml");
	
	@Test
	public void testDataSource() throws Exception 
		DataSource ds = ios.getBean("dataSource",DataSource.class);
		System.out.println("ds == "+ds);
		
		Connection connection = ds.getConnection();
		System.out.println("connection == "+connection);
		
	




测试成功

3.5、集成Mybatis-Plus

com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean

再次运行测试时会输出一下提示

四、入门HelloWorld

4.1 通用CRUDl
1)提出问题:
假设我们已存在一张tbl_emplovee表,且已有对应的实体类 Employee ,实现tbl_employee表的CRUD 操作找们需要做什么呢?。
2)实现方式:
基于 Mybatis
需要编写EmployeeMapper接口,并手动编写CRUD方法
提供 EmployeeMapper.xml映射文件,并手动编写每个方法对应的sQL 语句.
基于MP
只需要创建EmploveeMapper接口,并继承BaseMapper,接口.这就是使用MPv需要完成的所有操作,甚至不需要创建SQL映射文件。

4.1、BaseMapper接口


EmployeeMapper.java

package com.atguigu.mp.mapper;

import com.atguigu.mp.beans.Employee;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/*
 * Mapper接口
 * 
 * 基于Mybatis:	在Mapper接口中编写CRUD相关的方法提供Mapper接口所对应的SQL映射文件,以及方法对应的SQL语句。
 * 
 * 基于MP:		让XxxMapper接口继承BaseMapper接口即可。
 * 				BaseMapper<T>︰泛型指定的就是当前Mapper接口所操作的实体类类型
 * 
 */

public interface EmployeeMapper extends BaseMapper<Employee>



4.2、插入操作

4.2.1、通用插入操作(@TableName,@TableId)



运行测试,后数据库更新数据如下:

4.2.2、通用插入操作(通过application.cml配置代替@TableName,@TableId,实现同意设置)


4.2.3、bean上使用@TableField和@TableField注解

4.2.4、插入数据获取主键值

mybatisplus执行插入后会自动返回主键值

如果是mabatis的话需要用一下方式操作

4.3、更新操作

4.3.1、通用更新操作——update



4.4、查询操作

/*
	 * 通用查询方法
	 */
	@Test
	public void testCommonSelect()
		//1、通过id查询selectById
		Employee employee1 = employeeMapper.selectById(3);
		System.out.println("selectById == "+employee1);
		
//		//2、通过多个字段查询selectById
//		Employee employee2 = new Employee();
//		employee2.setLastName("Tony");
//		employee2.setAge(23);
//		
//		
//		Employee res = employeeMapper.selectOne(employee2);
//		System.out.println("selectOne == "+res);
		
		//3、通过多个id查询
		List<Integer> idList = new ArrayList<>();
		idList.add(1);
		idList.add(2);
		idList.add(3);
		
		List<Employee> employee3 = employeeMapper.selectBatchIds(idList);
		System.out.println("selectBatchIds == "+employee3);
		
		//4、通过Map查询
		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("last_name", "Tom");//key写的是数据库的列名,不是对象的属性名
		columnMap.put("gender", "1");
		
		List<Employee> employee4 = employeeMapper.selectByMap(columnMap);
		System.out.println("selectByMap == "+employee4);
		
		//5、通过selectPage查询
//		List<Employee> employee5 = (List<Employee>) employeeMapper.selectPage(new Page<>(1, 2), null);
//		System.out.println("selectByMap == "+employee4);
		
		
	

4.5、删除操作

	/*
	 * 通用删除方法
	 */
	@Test
	public void testCommonDelete()
		//通过deleteById删除一条数据
		Integer deleteById = employeeMapper.deleteById(3);
		System.out.println("deleteById == "+deleteById);
		
		//通过deleteByMap根据条件删除数据
		Map<String, Object> columnMap = new HashMap<String, Object>();
		columnMap.put("last_name", "MP");//key写的是数据库的列名,不是对象的属性名
		columnMap.put("gender", "1");
		Integer deleteByMap = employeeMapper.deleteByMap(columnMap);
		System.out.println("deleteByMap == "+deleteByMap);
		
		//通过deleteBatchIds根据多个id删除数据
		List<Integer> idList = new ArrayList<>();
		idList.add(8);
		idList.add(9);
		
		int deleteBatchIds = employeeMapper.deleteBatchIds(idList);
		System.out.println("deleteBatchIds == "+deleteBatchIds);
	

五、条件构造器

5.1、QueryWrapper

5.1.1、QueryWrapper带条件查询操作selectList



5.1.2、QueryWrapper带条件更新操作update

5.1.3、QueryWrapper带条件更新操作delete

六、ActiveRecord(活动记录)

6.1、AR插入操作

6.2、AR更新操作

6.3、AR查询操作

6.3.1、AR查询操作selectById

6.3.2、AR查询操作selectAll

6.3.3、AR查询操作selectList

6.3.4、AR查询操作selectCount

以上是关于Mybatis-Plus学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis-Plus-自动填充功能(学习笔记)

MyBatis-Plus-自动填充功能(学习笔记)

MyBatis-Plus-自动填充功能(学习笔记)

MyBatisPlus学习笔记

mybatis-plus学习笔记

Mybatis-Plus学习笔记