Mybatis-Plus myBatis enhancement tools

1.  Mybatis-Plus Profile

1.1.  What is Mybatis-Plus

Plus-MyBatis (abbreviated MP ) is a  MyBatis  enhancement tool, MyBatis based on only enhance not changed , to simplify development, increase efficiency and health.

 

1.2.  Why learn Mybatis-Plus

We have learned Mybatis this framework, we only need dao defines an abstract interface layer, based on Mybatis zero achieve characteristics can be achieved on the database crud operations.

The following two interfaces:

 

UserMapper Interface

public interface UserMapper {

 

    int deleteByPrimaryKey(Long id);

    int insert(User user);

    List<User> selectList();

    User selectByPrimaryKey(Long id);

}

 

OrderMapper Interface

public interface OrderMapper {

 

    int deleteByPrimaryKey(Long id);

    int insert(Order order);

    List<Order> selectList();

    User selectByPrimaryKey(Long id);

}

 

In the above two business interface, we found that: they define a set of similar crud method.

 

In more type of business, when this group of functionally similar interface methods we need to repeat the definition.

 

How to solve this problem?

 

Use Mybatis-plus tools, we only need to define the abstract interface we inherit a common BaseMapper <T> interface, you can get a common set of crud way to operate the database! ! !

 

Use Mybatis-plus time, do not even need any xml mapping files or annotations interface methods, the real the dao layer to achieve zero.

 

public interface OrderMapper extends BaseMapper<User> {

   // BaseMa of the Clipper has achieved a universal method of the curd. If there is a non-general-purpose operating needs, just here custom

}

 

 

1.3.  Mybatis-Plus Summary

Mybatis-Plus just Mybatis based on the realization of enhancements, allowing developers to more simple and efficient.

 

Mybatis-Plus does not modify Mybatis any property! ! !

2.  Introductory Examples

2.1.  Demand

Use Mybatis-Plus to achieve the user's crud operations.

 

2.2  Configuration step described

( 1 ) build environment (creating a project, import the package)

( 2 ) Configuration Mybaits-Plus (based Spring implementation)

( 3 ) writing test code

 

2.3  Configuration step

2.3.1.  The first part : built environment

2.3.1.1.  Premise

We have created a database environment:

CREATE TABLE `tb_user` (

  `id` bigint(20) NOT NULL COMMENT '主键ID',

  `name` varchar(30) DEFAULT NULL COMMENT '姓名',

  `age` int (11) DEFAULT NULL COMMENT ' Age '

  `email` varchar (50) DEFAULT NULL COMMENT ' mailbox ',

  PRIMARY KEY (`id`)

)

2.3.1.2.  Description

( . 1 ) Mybatis-Plus does not provide a separate jar package, but through Maven (or Gradle ) to manage jar dependent. This tutorial requires the use Maven to build the project.

 

( 2 ) Mybatis-Plus is based on the Spring Framework implementation, the use Mybatis-Plus , it must import Spring its dependencies.

 

2.3.1.3. 第一步:创建一个Maven项目

因为我们只是测试MybatisPlus框架,所以创建一个jar项目就可以了

 

 

2.3.1.4. 第二步:配置pom.xml构建文件

--需要导入依赖,并且配置项目的编码,JDK版本等构建信息

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>org.chu.mybatisplus</groupId>

<artifactId>mybatisplus-demo-01-start</artifactId>

<version>1.0</version>

 

<!-- 依赖 -->

<dependencies>

<!-- spring依赖 -->

 

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>4.3.24.RELEASE</version>

</dependency>

 

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.3.24.RELEASE</version>

</dependency>

 

<!-- mybatis plus -->

<dependency>

<groupId>com.baomidou</groupId>

<artifactId>mybatis-plus</artifactId>

<version>2.3.3</version>

</dependency>

 

<!-- mysql driver -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.47</version>

</dependency>

 

</dependencies>

 

<!-- 只有配置了build标签里面的内容,配置后都需要强制更新项目 -->

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.8.1</version>

<configuration>

<!-- 设置编码 -->

<encoding>UTF-8</encoding>

<!-- JDK版本 -->

<source>1.8</source>

<target>1.8</target>

</configuration>

</plugin>

<!-- 安装install命令的时候跳过单元测试 -->

 

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>2.22.2</version>

<configuration>

<skipTests>true</skipTests>

</configuration>

</plugin>

</plugins>

</build>

</project>

 

2.3.2. 第二部分:配置整合部分

整合MybatisPlusSpring的配置。创建一个spirng-data.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">

 

     <!-- 第一步:配置数据源 -->

     <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

       <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

       <property name="url" value="jdbc:mysql://localhost:3306/mybatis-plus"></property>

       <property name="username" value="root"></property>

       <property name="password" value="123456"></property>

       <!-- 最大激活的连接数 -->

       <property name="maxActive" value="10"></property>

       <!-- 最大空闲连接数据 -->

<!--        <property name="maxIdle" value="5"></property> -->

       <!-- 超时毫秒数 -->

       <property name="maxWait" value="30000"></property>

     </bean>

     <!-- 第二步:获得会话工厂 -->

     <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">

       <!-- 指定数据源 -->

       <property name="dataSource" ref="dataSource"></property>

     </bean>

     

     <!-- 第三步:扫描动态映射对象到Spring容器 -->

     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

       <!-- 指定会话工厂 -->

       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

       <!-- 指定扫描的映射包 -->

       <property name="basePackage" value="org.chu.mybatisplus.mapper"></property>

     </bean>

     

     <!-- 第四步:配置事务代理 -->

     <bean name="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

       <property name="dataSource" ref="dataSource"></property>

     </bean>

     <tx:annotation-driven transaction-manager="tx"/>

</beans>

 

2.3.3. 第三部分:实现操作功能

说明:完成实验MybatisPlus对数据库增删改查。

 

2.3.3.1. 第一步:编写POJO

说明:使用Mybatis-Plus不使用xml文件,而是基于一组注解来解决实体类数据库表映射问题。

 

@TableName(value="tb_user")

指定对应的表,表名和类名一致时,可以省略value属性。

@TableId

指定表的主键。Value属性指定表的主键字段,和属性名一致时,可以省略。Type指定主键的增长策略。

@TableField

指定类的属性映射的表字段,名称一致时可以省略该注解。

 

package org.chu.mybatisplus.pojo;

 

import com.baomidou.mybatisplus.annotations.TableField;

import com.baomidou.mybatisplus.annotations.TableId;

import com.baomidou.mybatisplus.annotations.TableName;

import com.baomidou.mybatisplus.enums.IdType;

 

@TableName(value="tb_user")

public class User {

 

   /*--

       AUTO->`0`("数据库ID自增")

       INPUT->`1`(用户输入ID")

       ID_WORKER->`2`("全局唯一ID")

       UUID->`3`("全局唯一ID")

       NONE-> 4 ("不需要ID")

   --*/

@TableId(value="id",type=IdType.AUTO)

private Long id;//BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',

//如果属性名与数据库表的字段名相同可以不写

@TableField(value="name")

private String name;//VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',

@TableField(value="age")

private Integer age;//INT(11) NULL DEFAULT NULL COMMENT '年龄',

@TableField(value="email")

private String email;//VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',

    //补全get/set方法

}

 

 

2.3.3.2. 第二步:编写Mapper接口

package org.chu.mybatisplus.mapper;

import org.chu.mybatisplus.pojo.User;

import com.baomidou.mybatisplus.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {

 

}

2.3.3.3. 第三步:测试增删改查

package org.chu.test.mapper;

import java.util.List;

 

import org.chu.mybatisplus.mapper.UserMapper;

import org.chu.mybatisplus.pojo.User;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

 

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import com.baomidou.mybatisplus.mapper.Wrapper;

//注意事项:Maven的单元测试包必须放置测试源码包里面

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations="classpath:spring-data.xml")

public class UserMapperTest {

 

@Autowired

private UserMapper userMapper;

 

@Test

public void insert() {

try {

User user=new User();

user.setName("wangwu");

user.setAge(20);

user.setEmail("[email protected]");

Integer insert = userMapper.insert(user);

System.out.println(insert);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

@Test

public void deleteById() {

try {

Integer count = userMapper.deleteById(1L);

System.out.println(count);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

@Test

public void deleteByCondition() {

try {

//设置条件

EntityWrapper<User> wrapper=new EntityWrapper<>();

wrapper.like("name", "%wang%");

Integer count = userMapper.delete(wrapper);

System.out.println(count);

} catch (Exception e) {

e.printStackTrace();

}

}

 

@Test

public void update() {

User user=new  User();

user.setName("wangwu");

user.setEmail("[email protected]");

user.setId(2L);

userMapper.updateById(user);

 

}

 

@Test

public void findAll() {

List<User> users = userMapper.selectList(null);

for (User user : users) {

System.out.println(user.getName());

}

}

 

}

 

 

3. 常用配置

3.1. 实体类全局配置

如果在配置文件指定实体类的全局配置,那么可以不需要再配置实体类的关联注解。

--配置文件spring-data.xml的修改

   <!-- 第二步:获得会话工厂 -->

     <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">

       <!-- 指定数据源 -->

       <property name="dataSource" ref="dataSource"></property>

       <!-- 全局实体类配置 -->

       <property name="globalConfig" >

          <bean class="com.baomidou.mybatisplus.entity.GlobalConfiguration">

            <!--

            AUTO->`0`("数据库ID自增")

             INPUT->`1`(用户输入ID")

            ID_WORKER->`2`("全局唯一ID")

            UUID->`3`("全局唯一ID")

         -->

            <property name="idType" value="0"></property>

            <!-- 实体类名与表名的关联规则是,忽略前缀 -->

            <property name="tablePrefix" value="tb_"></property>

          </bean>

       </property>

     </bean>

--实体类就可以去掉关联的注解了

package org.chu.mybatisplus.pojo;

public class User {

private Long id;

private String name;

private Integer age;

private String email;

//补全getset方法

}

 

3.2. 插件配置

Mybatis默认情况下,是不支持物理分页的。默认提供的RowBounds这个分页是逻辑分页来的。

 

所谓的逻辑分页,就是将数据库里面的数据全部查询出来后,在根据设置的参数返回对应的记录。(分页是在程序的内存中完成)。【表数据过多时,会溢出】

 

所谓的物理分页,就是根据条件限制,返回指定的记录。(分页在数据库里面已经完成)

 

MybatisPlus是默认使用RowBounds对象是支持物理分页的。但是需要通过配置Mybatis插件来开启。

 

 

配置代码

     <!-- 第二步:获得会话工厂 -->

     <bean name="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">

       <!-- 指定数据源 -->

       <property name="dataSource" ref="dataSource"></property>

       <!-- 全局实体类配置 -->

       <property name="globalConfig" >

          <bean class="com.baomidou.mybatisplus.entity.GlobalConfiguration">

            <!--

            AUTO->`0`("数据库ID自增")

             INPUT->`1`(用户输入ID")

            ID_WORKER->`2`("全局唯一ID")

            UUID->`3`("全局唯一ID")

         -->

            <property name="idType" value="0"></property>

            <!-- 实体类名与表名的关联规则是,忽略前缀 -->

            <property name="tablePrefix" value="tb_"></property>

          </bean>

       </property>

       <!-- 配置插件 -->

       <property name="plugins">

          <list>

            <!-- 分页的支持 -->

            <bean class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">

               <!-- 方言 -->

               <!-- 我们使用的是MySQL数据库,所以需要配置MySQL的方言 -->

               <property name="dialectClazz" value="com.baomidou.mybatisplus.plugins.pagination.dialects.MySqlDialect"></property>

            </bean>

            <!-- 配置支持SQL输出 -->

            <bean class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">

               <property name="format" value="true"></property>

            </bean>

          </list>

       </property>

     </bean>

 

3.3. 自定义SQL语句支持

--实现代码

package org.chu.mybatisplus.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import org.chu.mybatisplus.pojo.User;

import com.baomidou.mybatisplus.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {

@Select(value="select * from tb_user")

List<User> findAll();

}

--测试代码

package org.chu.test.mapper;

import java.util.List;

 

import org.chu.mybatisplus.mapper.UserMapper;

import org.chu.mybatisplus.pojo.User;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//注意事项:Maven的单元测试包必须放置测试源码包里面

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations="classpath:spring-data.xml")

public class UserMapperTest {

@Autowired

private UserMapper userMapper;

@Test

public void findAll() {

 

try {

List<User> users = userMapper.findAll();

for (User user : users) {

System.out.println(user.getName());

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

Guess you like

Origin www.cnblogs.com/aknife/p/11227814.html
Recommended