SpringBoot整合TKMyBatis实现单表增删改查操作

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot整合TKMyBatis实现单表增删改查操作

欲无缘   2023-02-02 我要评论

什么是TKMybatis

TKMybatis 是基于Mybatis 框架开发的一个工具,内部实现了对单表的基本数据操作,只需要简单继承 TKMybatis 提供的接口,就能够实现无需编写任何 sql 即能完成单表操作。

SpringBoot整合TKMybatis

添加maven依赖

    <dependency>
      <groupId>tk.mybatis</groupId>
      <artifactId>mapper-spring-boot-starter</artifactId>
      <version>2.1.5</version>
    </dependency>

实体类注解

@Setter
@Getter
@Table(name = "user")
public class User {
    /**
     * 用户ID
     */
    @Id
    private String id;
    /**
     * 用户姓名
     */
    private String userName;
    /**
     * 用户密码
     */
    private String passWord;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 性别
     */
    private String gender;
}

@Table:描述数据库表信息,主要属性有name(表名)、schema、catalog、uniqueConstraints等。

@Id:指定表主键字段,无属性值。

@Column:描述数据库字段信息,主要属性有name(字段名)、columnDefinition、insertable、length、nullable(是否可为空)、precision、scale、table、unique、updatable等。

@ColumnType:描述数据库字段类型,可对一些特殊类型作配置,进行特殊处理,主要属性有jdbcType、column、typeHandler等。

其他注解如:@Transient、@ColumnResult、@JoinColumn、@OrderBy、@Embeddable等暂不描述

TKMapper接口如何使用

单表操作,只需要继承 tk.mybatis 下的 BaseMappe接口即可使用

@Mapper
public interface UserMapper extends Mapper<User>, MySqlMapper {
}

基本增删改操作

@Service
public class UserService {
    @Resource
    private UserMapper userMapper;
    /**
     *  根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
     */
    public User selectUserById(String userId){
        return userMapper.selectByPrimaryKey(userId);
    }
    /**
     *  查询全部结果
     */
    public List<User> selectAll(){
        return userMapper.selectAll();
    }
    /**
     *  根据实体中的属性值进行查询,查询条件使用等号
     */
    public List<User> selectByUserName(String userName){
        User user = new User();
        user.setUserName(userName);
        return userMapper.select(user);
    }
    /**
     *  根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号。
     *  但是如果存在某个属性为int,则会初始化为0。可能影响到实际使用
     */
    public User selectOneByUserName(String userName){
        User user = new User();
        user.setUserName(userName);
        return userMapper.selectOne(user);

    }
    /**
     *  根据实体中的属性查询总数,查询条件使用等号
     */
    public Integer selectUserCount(String userName){
        User user = new User();
        user.setUserName(userName);
        return userMapper.selectCount(user);
    }
    /**
     *  保存一个实体,null的属性也会保存,不会使用数据库默认值
     */
    public void addUser(String userName,String passWord,Integer age,String gender){
        User user = new User();
        user.setId(String.valueOf(UUID.randomUUID()));
        user.setUserName(userName);
        user.setAge(age);
        user.setGender(gender);
        user.setPassWord(passWord);
        userMapper.insert(user);
    }
    /**
     *  保存一个实体,忽略空值,即没提交的值会使用使用数据库默认值
     */
    public void addUserService(String userName,String passWord){
        User user = new User();
        user.setId(String.valueOf(UUID.randomUUID()));
        user.setUserName(userName);
        user.setPassWord(passWord);
        userMapper.insertSelective(user);
    }
    /**
     *  根据主键字段进行删除,方法参数必须包含完整的主键属性
     */
    public void deleteById(String userId){
        userMapper.deleteByPrimaryKey(userId);
    }
    /**
     *  根据实体属性作为条件进行删除,查询条件使用等号
     */
    public void deleteByName(String userName){
        User user = new User();
        user.setUserName(userName);
        userMapper.delete(user);
    }
    /**
     *  根据主键更新实体全部字段,null值会被更新
     */
    public void updateById(String userId,String userName){
        User user = new User();
        user.setId(userId);
        user.setUserName(userName);
        userMapper.updateByPrimaryKey(user);
    }
    /**
     *  根据主键更新属性不为null的值
     */
    public void updateByIdSelective(String userId,String userName){
        User user = new User();
        user.setId(userId);
        user.setUserName(userName);
        userMapper.updateByPrimaryKeySelective(user);
    }    
}

批量查询和删除

批量查询 批量删除集成 SelectByIdsMapper, DeleteByIdsMappe 接口

@Mapper
public interface UserMapper extends Mapper<User>, SelectByIdsMapper, DeleteByIdsMapper {
}
     /**
     *  批量查询
     */
    public List<User> selectUserById(List<String> userIds){
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String userId : userIds) {
            stringJoiner.add(userId);
        }
        return userMapper.selectByIds(stringJoiner.toString());
    }
    /**
     *  根据ID批量删除
     */
    public void deleteById(List<String> userIds){
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String userId : userIds) {
            stringJoiner.add(userId);
        }
        userMapper.deleteByIds(stringJoiner.toString());
    } 

批量添加

批量添加需要继承MySqlMappe接口

@Mapper
public interface UserMapper extends Mapper<User>, MySqlMapper, SelectByIdsMapper, DeleteByIdsMapper {
}
    /**
     *  批量添加
     */
    public void batchAdd(){
       List<User> list = new ArrayList();
        for (int i = 1; i < 6; i++) {
            User user = new User();
            user.setId(String.valueOf(i));
            user.setUserName("zs");
        }
        userMapper.insertList(list);
    }

自定义查询条件Example

图中接口都有一个共同点,就是需要 Example 对象作为方法的参数,Example 对象包含了我们各种自定义的查询条件,相当于 sql 语句中 where 部分的条件。

每个接口都包含了一个方法,供我们调用。总结如下表:

方法功能描述
int deleteByExample(Object var1);一般参数就是Example对象,按照条件进行删除,返回删除的记录数
List selectByExample(Object var1);一般参数就是Example对象,按照条件进行查询,返回查询结果集
int selectCountByExample(Object var1);一般参数就是Example对象,按照条件进行查询,返回符合查询条件的记录数
T selectOneByExample(Object var1);一般参数就是Example对象,按照条件进行查询,结果只能为空或者一个,否则抛出异常
int updateByExample(@Param(“record”) T var1, @Param(“example”) Object var2);第一个参数是新记录,第二参数是example对象,用新记录替换掉符合条件的旧记录
int updateByExampleSelective(@Param(“record”) T var1, @Param(“example”) Object var2);功能同上,只是可以仅替换掉记录的部分字段
List selectByRowBounds(T var1, RowBounds var2);第一个参数是查询条件,第二个参数是 RowBounds 对象(包含2个属性,offset 和 limit),offset 表示起始行,limit 表示需要的记录数;方法的功能是按照查询条件进行查询,再按照 offset 和 limit 在结果集中取相应数量的记录。
List selectByExampleAndRowBounds(Object var1, RowBounds var2);第一个参数是 Example 对象,第二个参数是 RowBounds 对象,先根据 example 条件进行查询,再按照 offset 和 limit 取相应数量的记录。
List selectByConditionAndRowBounds(Object var1, RowBounds var2);同上

Example 条件设置

先创建 Example 对象,再创建 Example.criteria 对象,借助这两个对象,可以灵活地设置各种条件。Example 对象可以理解为 sql 语句层次的设置, 而 Example.criteria 对象可以理解为 sql 语句中的一个单一的条件表达式设置。

原理上可以理解为:一个 example 包含了若干个 criteria ,每个 criteria 就是 sql 语句中条件部分的一个括号部分(没有嵌套),比如 (id = 5),criteria 包含了一个方法 void setAndOr(String andOr),它的意思相当于在括号前面加上 and 还是 or,比如执行了方法 setAndOr(“and”),那么 criteria 相当于 and (id = 5),而 example 就把这些 criteria 拼凑起了,比如 example 包含了 2 个 criteria,分别是 (id = 5) 和 and (name = “张三”),那么此 example 的效果就是 (id = 5) and (name = “张三”)。

Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
方法功能描述
andAllEqualTo(Object param)所有字段都作为 where 后面的判断条件,判断值就是参数实体对象
andBetween(String property, Object value1, Object value2)where property between value1 and value2 ,范围条件,包含两端
andEqualTo(Object param)实体对象中不为 null 的字段作为 where 后面的判断条件
andEqualTo(String property, Object value)某一个<字段,值>作为 where 后面的判等条件
andGreaterThan(String property, Object value)大于条件,某个字段大于某个值
andGreaterThanOrEqualTo(String property, Object value)大于等于条件,某个字段大于等于某个值
andIn(String property, Iterable values)where property in (),范围条件
andIsNotNull(String property)where property is not null,判空条件
andIsNull(String property)where property is null,判空条件
andLessThan(String property, Object value)小于条件
andLessThanOrEqualTo(String property, Object value)小于等于条件
andLike(String property, String value)where property like value,注意 value 应该是一个匹配表达式
andNotBetween(String property, Object value1, Object value2)范围条件,不包含两端
andNotEqualTo(String property, Object value)要求字段不等于某个值
andNotIn(String property, Iterable values)要求字段不在某个范围内
andNotLike(String property, String value)模糊查询,要求不 like。
void setAndOr(String andOr)上面已经介绍过了

上表的方法都是“与”关系,即 and。 同样的,有相应的 “或” 关系,即 or。比如 orAllEqualTo、orGreaterThan 等等,都是将方法名中的 “and” 换成 “or”。

那 criteria 能否嵌套呢?能否有更方便的使用方式呢?回答:能,有。如下表:

方法功能描述
Example.Criteria orCondition(String condition, Object value)condition参数是个sql字符串,可以拼接进 sql 语句的,value 是一个值,会拼接到 condition 后面的,此方法的最终结果为 or condition + value。
Example.Criteria orCondition(String condition)功能同上,只是更加直接,一个字符串搞定,只是字符串参数可以写成类似这种 “id = ”+getId(),“( id = “+getId()+”)”,一样灵活,此方法的最终结果为 or condition。
Example.Criteria andCondition(String condition)不再赘述
Example.Criteria andCondition(String condition, Object value)不再赘述

Example 类包含的方法总结如下表:

方法功能描述
void setDistinct(boolean distinct)查询的结果是否要进行唯一性过滤,true表示过滤,false(默认)表示不过滤。
void setOrderByClause(String orderByClause)查询结果按照某个,或者某些字段进行升序,降序。比如参数是 “id asc” 就是按照 id 进行升序,“id asc,age desc” 就是按照 id 升序,在 id 相等的情况下,按照 age 降序。
Example selectProperties(String… properties)当利用 example 进行查询时,此方法可以设置想要查询的字段是哪些,比如我只需要查询一张表的部分字段。
Example.OrderBy orderBy(String property)排序,与 setOrderByClause 功能一样,只是用法不同,比如 orderBy(“id”).asc() 表示按照 id 升序, orderBy(“id”).asc().orderBy(“age”).desc() 表示按照 id 升序,再按照 age 降序
Example.Criteria or()创建一个 or 方式的、空的criteria,具体的 criteria 内容可以稍后设置。
void or(Example.Criteria criteria)直接以 or 的方式添加一个现有的 criteria
Example.Criteria and()同上,不过是 and 方式
void and(Example.Criteria criteria)同上,and 方式

Example 使用

    public List<User> getUserByExample(String userName,String age){
        Example example = new Example(User.class);
        //Example.Criteria criteria = example.and();  
        //criteria.andEqualTo("age",age)  这里直接简写了
        example.and().andEqualTo("age",age)
                .andLike("userName",'%' +userName + '%');
        List<User> users = userMapper.selectByExample(example);
        return users;
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们