springboot整合tkmybatis以及使用

经常用mybatis的的都知道,使用mybatis orm框架存在一个非常不友善的问题就是,就是每操作一个单表就需要自己手写一个xml文件,虽然说可以用工具生成xml和实体类可以解决这个问题,但是二次开发的时候对某个表字段进行修改的时候,生成xml文件就不现实啦。最近发现tkmybatis就非常好的解决了这个问题。在这里和大家分享一下。

  • 框架配置

这里需要引用到的包

 <!--mybatis操作数据库有关-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--连接mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--使用阿里巴巴的druid数据源,有利于监控sql的执行情况-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <!--添加lombok支持,可以省掉写get和set方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <optional>true</optional>
        </dependency>
        <!--使用fastjson来操作json数据-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>

        <!--spring boot web方面的支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>

数据源配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

表结构语句

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `user_phone` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `user_name_index`(`user_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'evan', '26');
INSERT INTO `user` VALUES (2, 'evan11', '26');

  • 类配置方法
    实体类方法
    注意这里是引用了lombok框架,可以省略写get,set之类的方法,这里需要idea里面添加lombok插件,如果有报错的话。(如果有强迫症的话)其实还是代码还是可以跑起来的。
@Data
@Table(name="user")
public class UserModel  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY,generator = "JDBC")
    private Integer id;
    @Column
    private String userName;
    @Column
    private String userPhone;

}

其中@Table即数据表表名,@Column即列名,@Id作为主键,需要注意,@Id注解不可有多个,@Transient即冗余字段,不与数据库任何字段对应。
注意多数据源的情况:则@Table注解中可以写成“{数据库名}.{架构名}.{表名}”,如:@Table(name=“db.dbo.tableName”)

在这里插入图片描述

  • Service类
    这里主要是实现了上边BaseMapper中继承的5个Mapper的方法。
    tk.mybatis.mapper.common.BaseMapper中有较多方法,均需要继承实现:
 /**
	 * 保存一个实体,null属性也会保存
	 * 
	 * @param record
	 * @return
	 */
	int insert(T record);
 
	/**
	 * 保存一个实体,null属性不会保存
	 * 
	 * @param record
	 * @return
	 */
	int insertSelective(T record);
 
	/**
	 * 根据实体属性作为条件进行删除,查询条件使用等号
	 */
	int delete(T record);
 
	/**
	 * 根据主键更新属性不为null的值
	 */
	int updateByPrimaryKeySelective(T record);
 
	/**
	 * 根据实体中的属性值进行查询,查询条件使用等号
	 */
	List<T> select(T record);
 
	/**
	 * 查询全部结果,select(null)方法能达到同样的效果
	 */
	List<T> selectAll();
 
	/**
	 * 根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
	 */
	T selectOne(T record);
 
	/**
	 * 根据实体中的属性查询总数,查询条件使用等号
	 */
	int selectCount(T record);

MySqlMapper中的方法如下:

/**
	 * 批量插入,支持批量插入的数据库可以使用,例如MySQL,H2等,另外该接口限制实体包含`id`属性并且必须为自增列
	 */
	public int insertList(List<T> recordList);
 
	/**
	 * 插入数据,限制为实体包含`id`属性并且必须为自增列,实体配置的主键策略无效
	 */
	public int insertUseGeneratedKeys(T record);

IdsMapper中的方法如下:

 /**
	 * 根据主键@Id进行查询,多个Id以逗号,分割
	 * @param id
	 * @return
	 */
	List<T> selectByIds(String ids);
	
	/**
	 * 根据主键@Id进行删除,多个Id以逗号,分割
	 * @param id
	 * @return
	 */
	int deleteByIds(String ids);

ConditionMapper中的方法如下:

/**
	 * 根据Condition条件进行查询
	 */
	public List<T> selectByCondition(Object condition);
 
	/**
	 * 根据Condition条件进行查询
	 */
	public int selectCountByCondition(Object condition);
 
	/**
	 * 根据Condition条件删除数据,返回删除的条数
	 */
	public int deleteByCondition(Object condition);
 
	/**
	 * 根据Condition条件更新实体`record`包含的全部属性,null值会被更新,返回更新的条数
	 */
	public int updateByCondition(T record, Object condition);
 
	/**
	 * 根据Condition条件更新实体`record`包含的全部属性,null值会被更新,返回更新的条数
	 */
	public int updateByConditionSelective(T record, Object condition);

ExampleMapper中的方法如下:

/**
	 * 根据Example条件进行查询
	 */
	public List<T> selectByExample(Object example);
 
	/**
	 * 根据Example条件进行查询,若有多条数据则抛出异常
	 */
	public T selectOneByExample(Object example);
 
	/**
	 * 根据Example条件进行查询总数
	 */
	public int selectCountByExample(Object example);
 
	/**
	 * 根据Example条件删除数据,返回删除的条数
	 */
	public int deleteByExample(Object example);
 
	/**
	 * 根据Example条件更新实体`record`包含的全部属性,null值会被更新,返回更新的条数
	 */
	public int updateByExample(T record, Object example);
 
	/**
	 * 根据Example条件更新实体`record`包含的不是null的属性值,返回更新的条数
	 */
	public int updateByExampleSelective(T record, Object example);

使用方法

tk.mybatis.mapper.common.BaseMapper, IdsMapper, MySqlMapper内方法使用说明:
从接口中我们可以看到传入的方法基本均为T record,即实体类,查询时会根据实体类中的属性值进行where语句构建,查询条件为等号,这里没什么特殊的。

ExampleMapper内方法使用说明:

 Example example = new Example(UserModel.class);
 Example.Criteria criteria = example.createCriteria();
 criteria.andEqualTo("id","1");
 criteria.orEqualTo("userName","evan11");

Criteria是Example中的一个内部类,在最终sql构建时以括号呈现,Criteria里带了较多构建查询条件的方法:
在这里插入图片描述
ExampleMapper内方法使用说明:
所有方法均需要传入tk.mybatis.mapper.entity.Example,

Example example = new Example(UserRole.class);//实例化
Example.Criteria criteria = example.createCriteria();

Criteria是Example中的一个内部类,在最终sql构建时以括号呈现,Criteria里带了较多构建查询条件的方法,如
andEqualTo(String property,Object value)
orEqualTo(String property,Object value)
andGreaterThan(String property, Object value)
orGreaterThan(String property, Object value)
举例说明

 Example example = new Example(UserModel.class);
 Example.Criteria criteria = example.createCriteria();
 criteria.andEqualTo("id","1");
 criteria.orEqualTo("userName","evan11");
 List<UserModel> userModels = userDao.selectByExample(example);

最总输出的sql语句是

Preparing: SELECT id,user_name,user_phone FROM user WHERE ( ( id = ? and user_name = ? ) ) 
Parameters: 1(String), evan11(String)

其中andCondition(String condition)方法支持手写条件,传入的字符串为最终的查询条件,如:length(f_user_id)<5

以及likeTo()的方法是不带百分号%的,需要自己对传入参数进行构建(加左like或者右like等)。

其余方法自行见源码,不再赘述。

ConditionMapper内方法使用说明:
所有方法均需要传入tk.mybatis.mapper.entity.Condition,Condition实际上继承自tk.mybatis.mapper.entity.Example,
源码中有三个方法:


public Condition(Class<?> entityClass) {
    super(entityClass);
}
 
public Condition(Class<?> entityClass, boolean exists) {
    super(entityClass, exists);
}
 
public Condition(Class<?> entityClass, boolean exists, boolean notNull) {
    super(entityClass, exists, notNull);
}

其使用方法与Example类似


Condition condition = new Condition(UserRole.class);
Criteria criteria = condition.createCriteria();
 criteria.andEqualTo("id","1");
 criteria.orEqualTo("userName","evan11");
 List<UserModel> userModels = userDao.selectByExample(example);
  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值