通用Mapper的使用

作用

在使用mybatis写数据库的CRUD时候,简单的一些语句是十分繁琐且乏味的事情。

该通用Mapper会帮你自动实现简单的CRUD语句,让开发更加高效。

使用方法

1、导入依赖

在pom.xml文件中加入依赖:

<!--通用mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2、继承通用Mapper类

将对应数据的的Mapper接口继承tk的通用Mapper接口:

import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User>
{
    //集成tk的通用Mapper,自动实现基础的CRUD

}

其中User是对应数据库表的映射bean类。

3、为通用Mapper指定Bean类信息

需要指定Bean类的主键等信息让查询更加完整:

例如:在User类中指定ID和自增长:

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;

public class UmsMember
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String id;
    private String memberLevelId;
    private String username;
    private String password;
    private String nickname;
}

4、使用通用Mapper的MapperScan

在项目扫描mapper的注解MapperScan中使用tk.Mybatis的MapperScan:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//使用tk.mybatis包
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan(basePackages = "com.lin.test.mapper")
public class TestApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(TestApplication.class, args);
    }

}

5、使用CRUD方法

在上述操作完成后,在使用UserMapper的类中就可直接调用自动实现的CRUD方法:

原文地址:https://www.cnblogs.com/jinchengll/p/12276171.html