概念:

使用 Mybatis 时,最大的问题是,要写大量的重复 SQL 语句在 xml 文件中,除了特殊的业务逻辑 SQL 语句之外,还有 大量结构类似的增删改查SQL 。而且,当数据库表结构改动时,对应的所有 SQL 以及实体类都需要更改。
这大量增 加了程序员的负担。避免重复书写CRUD 映射的框架有两个
通用 mybatis tk mybatis
mybatis plus ,通能更加强大

一.tk-mybatis的使用

1.tk-mybatis需要引入启动器,直接引入即可。

pom.xml中引入如下内容

<!-- 通用 mapper -->
<dependency>
        <groupId> tk.mybatis </groupId>
        <artifactId> mapper-spring-boot-starter </artifactId>
        <version> 2.0.2 </version>
</depe
ndency>

2. 创建实体类

tk mybatis 实体类使用的注解是jpa注解   JPA注释详解参考手册

@Table ( name = "tb_user" )
public class User implements Serializable {
private static final long serialVersionUID = 1L ;
@Id
@GeneratedValue ( strategy = GenerationType . IDENTITY )
private Long id ;
// 用户名
private String userName ;
....
注意事项:
1. 默认表名 = 类名,字段名 = 属性名
2. 表名可以使用 @Table(name = "tableName") 进行指定
实体类名称跟数据库中的表名称不相等的时候,使用此注解  name="数据库中的表名称"
3. @Column(name = "fieldName")   
指定字段跟属性对应匹配,数据库的字段跟属性不相等的时候,使用此注解  name="数据库字段名称"
4. 使用 @Transient 注解表示跟字段不进行映射      
如果实体类同的属性在数据库的表格中没有对应的字段,对属性使用此注解

3.创建接口实现继承

extends tk . mybatis . mapper . common . Mapper <实体类>
@Mapper
public interface UserMapper extends tk . mybatis . mapper . common . Mapper < User > {
public List < User > findByUser ( User user );
}

如果有自定义的映射文件方法,就在接口中设置方法,然后配置对应的xml文件。

没有自定义的方法,此接口中不用写任何内容。

自定义映射文件: 映射复杂方法  文件路径:  resources/mappers/UserMapper.xml

注意:此处的xml文件名称要和接口名称相同,xml中的id要与接口中的方法名称相同。

注意:如果使用mapperScan注解而不是Mapper要把MapperScan类改成tk-mybatis构件的类

例如:@MapperScan("com.lxs.demo.dao")      加到springBoot启动类Application上。 

@MapperScan和@Mapper的区别就是   :后者是单个类接口的实现,前者是包扫描的接口的实现的。

此处是自定义的xml方法,通过判断name,和note不为null的情况下,进行对name,note的模糊查询。

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<mapper namespace="com.lxs.demo.dao.UserMapper"> 
<select id="findByUser" resultType="user">
 SELECT *FROM tb_user 
    <where> 
        <if test="name != null">
         name like '%${name}%'
         </if>
        <if test="note != null">
         and note like '%${note}%'
         </if> 
    </where> 
</select> 
</mapper>

一旦继承了tk-mybatis  Mapper,继承的Mapper就拥有了该Mapper所有的通用方法:

 

Select
方法: List<T> select(T record);
说明:根据实体中的属性值进行查询,查询条件使用等号
方法: T selectByPrimaryKey(Object key) ;
说明:根据主键字段进行查询,方法参数必须包含完整的主键属性, 查询条件使用等号
方法: List<T> selectAll();
说明:查询全部结果, select(null) 方法能达到同样的效果
方法: T selectOne(T record);
说明:根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异 常,查询条件使用等号
方法: int selectCount(T record) ;
说明:根据实体中的属性查询总数,查询条件使用等号
Insert
方法: int insert(T record);
说明:保存一个实体, null 的属性也会保存,不会使用数据库默认值
方法: int insertSelective(T record) ;
说明:保存一个实体, null 的属性不会保存,会使用数据库默认值
Update
方法: int updateByPrimaryKey(T record) ;
说明:根据主键更新实体全部字段, null 值会被更新
方法: int updateByPrimaryKeySelective(T record) ;
说明:根据主键更新属性不为 null 的值
Delete
方法: int delete(T record);
说明:根据实体属性作为条件进行删除,查询条件使用等号
方法: int deleteByPrimaryKey(Object key) ;
说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
Example
方法: List<T> selectByExample(Object example) ;
说明:根据 Example 条件进行查询 重点:这 个查询支持通过 Example 类指定查询列,通过 selectProperties 方法指定查询列
方法: int selectCountByExample(Object example);
说明:根据 Example 条件进行查询总数
方法: int updateByExample(@Param("record") T record, @Param("example") Object example); 说明:根据 Example条件更新实体 record 包含的全部属性, null 值会被更新
方法: int updateByExampleSelective(@Param("record") T record, @Param("example") Object example) ;
说 明:根据Example 条件更新实体 record 包含的不是 null 的属性值
方法: int deleteByExample(Object example) ;
说明:根据 Example 条件删除数据
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {
@Autowired
private UserMapper userMapper;
//自定义的方法测试
@Test
public void testFindByUser() {
        User user = new User();
        user.setName("a");
        List<User> list = userMapper.findByUser(user);
        for (User user : list) {
        System.out.println(user);
                }
        }
@Test
public void testFindAll() {
        List<User> list = userMapper.selectAll();
        for (User user : list) {
        System.out.println(user);
                }
        }
@Test
public void testFindById() {
        User user = userMapper.selectByPrimaryKey(4);
        System.out.println(user);
        }
@Test
public void testFindByExample() {
        Example example = new Example(User.class);
        example.createCriteria().andLike("name", "%a%");
        userMapper.selectByExample(example).forEach(user -> {
        System.out.println(user);
});

二.mybatisplus的使用

Mybatis-Plus (简称 MP )是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,避免了我 们重复CRUD 语句。

1.引入mp的启动器。

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>

2.创建实体类

@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

此处的@data注解是对实体类的get和set方法的简化,使用此注解可以省略get和set方法的创建。使用时候直接使用即可,需要引入lombok依赖和对应的插件,这里不再具体说明。

MyBatisPlus 提供了一些注解供我们在实体类和表信息出现不对应的时候使用。通过使用注解完成逻辑上匹 配。
注解名称
说明
@TableName
实体类的类名和数据库表名不一致
@TableId
实体类中的成员名称和表中字段名称不一致>
@TableField
排除实体类中非表字段

排除实体类中非表字段   使用 @TableField(exist = false) 注解  前两个注解的使用和tkmybatis相似,不过@TableId的type默认主键策略 采取的是雪花算法。

3.创建接口继承 BaseMapper

其实是mybatisplus包下的BaseMapper

com.baomidou.mybatisplus.core.mapper.BaseMapper
public interface UserMapper extends BaseMapper<User> {
}

 4.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
        @Resource
        private UserMapper userMapper;
    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(6, userList.size());
        userList.forEach(System.out::println);
        }
}

继承了 MP的 BaseMapper,继承的Mapper就拥有了BaseMapper所有的通用方法: 

具体使用参考下面博文

MP 常用方法的使用   

gitee上的使用介绍:

mybatisplus:Mybatis-Plus

firstmybaits:firstmybaits

下面tk和mp的区别:

TKMybatis 和 MybatisPlus哪一个好用 - 代码先锋网

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐