Basic use of MybatisPlus

1. Mybatis – Plus concept

1.1 Mybatis – Plus is introduced

  • Official website: mybatis. Plus/mp.baomidou.com/

  • Mybatis – Plus is introduced

MyBatis-Plus (MP for short) is a MyBatis enhancement tool, on the basis of MyBatis only do enhancement do not change, to simplify the development and improve efficiency.

  • vision

Our vision is to become the best partner of MyBatis, just like 1P and 2P in Contra, the efficiency of gay friends is doubled.

1.2 features

1.3 architecture

  • Mybatis -plus-boot-starter specifies the dependent JAR package to be imported

  • Annotation module

  • Extension module

  • Core module

  • Generator Code Generator module

  • scan Entity

The database entity classes are scanned after the project starts

  • Analysis Table Name Column

After scanning, reflection is used to analyze entity classes, including Table, Colum and other relevant information. After knowing the relevant information, corresponding add, delete, change and search methods will be generated according to Table names and column names

  • Injection Mybatis Container

Add, delete, modify and check methods into Mybatis container for operation

1.4 Database Support

Therefore, Mybatis can support the database, Mybatis-Plus basically support

1.5 the author

Mybatis Plus was developed and opened source by the Baomidou organization, which currently has about 31 people. Code cloud address: gitee.com/organizatio…

2. Mybatis-Plus Quick Start

2.1 installation

Mybatis-Plus3.0 is based on JDK8 and provides lambda form calls, so the installation requirements for integrated MP3.0 are as follows

  • JDK 8+
  • Maven or Gradle

Spring MVC

Maven:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.4.0</version>
</dependency>
Copy the code

SpringBoot

Maven:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
Copy the code

Please do not introduce Mybatis and Mybatis-Spring after waring introduces Mybatis-Plus, in order to avoid version differences

There are often three usages for Mybatis integration MP, which are Mybatis+MP, Spring+Mybatis+MP, Spring Boot+Mybatis+MP.

2.2 Creating databases and tables

  • Creating an MP database

  • Create table User as follows:

2.3 Creating a Project

Import dependencies:

<dependencies>
  <! -- Mybatis - Plus plugin dependencies -->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.1.1</version>
  </dependency>
  <! --Mysql-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>
  <! -- Connection pool -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.11</version>
  </dependency>
  <! A toolkit for simplifying bean code
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.4</version>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
  </plugins>
</build>
Copy the code

Mybatis + 2.4 MP

The following demonstration, through pure Mybatis with Mybatis-Plus integration.

Log4j. Properties:

log4j.rootLogger=DEBUG,A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n
Copy the code

Mybatis implementation query User

  • Step 1: Compile mybatis-config.xml file:

      
<! DOCTYPEconfiguration
  PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <properties
    resource="jdbc.properties"></properties>
  <! -- Environments -->
  <environments
    default="development">
    <environment id="development">
      <! -- The current transaction manager is JDBC-->
      <transactionManager
        type="JDBC"></transactionManager>
      <! POOLED: use mybatis connection pool -->
      <dataSource type="POOLED">
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
      </dataSource>
    </environment>
  </environments>
  <! -- Import mapping configuration file -->
  <mappers>
    <mapper
      resource="mapper/UserMapper.xml"></mapper>
  </mappers>
</configuration>
Copy the code
  • Step 2, write the User entity object :(evolving bean operations using lombok here)
@Data
// Generate a no-parameter construct
@NoArgsConstructor
// Generate a parameterized construct
@AllArgsConstructor
public class User {
  private Long id;
  private String name;
  private Integer age;
  private String email;
}
Copy the code
  • Step 3: Write the UserMapper interface:
public interface UserMapper {
  List<User> findAll(a);
}
Copy the code
  • Step 4 write the usermapper.xml file:

      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lagou.mapper.UserMapper">
  <! Select * from 'all';
  <select id="findAll" resultType="com.mybatis.mp.User">
    select *
    from user
  </select>
</mapper>
Copy the code
  • Step 5: Write TestMybatis test cases
public class MybatisTest {

  @Test
  public void test1(a) throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> all = mapper.findAll();
    for(User user : all) { System.out.println(user); }}}Copy the code
  • Test results:

Note: you can annotate the entity class with @tablename (” specify database TableName “) if the entity class name does not match the TableName.

Mybatis+MP implementation query User

  • The first step is to inherit UserMapper from BaseMapper and have all the methods in BaseMapper:
public interface UserMapper extends BaseMapper<User > {
  List<User> findAll(a);
}
Copy the code
  • In the second step, the use of MP MybatisSqlSessionFactoryBuilder process construction:
  @Test
  public void test2(a) throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
/ / used here is MybatisSqlSessionFactoryBuilder of MP
    SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// You can call the methods defined in BaseMapper
    List<User> all = mapper.selectList(null);
    for(User user : all) { System.out.println(user); }}Copy the code
  • Testing:

Note: if the entity class name does not match the TableName, you can add a simple comment @tablename on the entity class:

With the use of MybatisSqlSessionFactoryBuilder build, inherited BaseMapper method of load to the SqlSession, so can directly use related methods; As shown in figure