spring boot 之mybatis注解开发

一、整合mybatis

1、添加依赖

 
<!--mybatis-->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.2.0</version>
</dependency>

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

2、添加mybatis配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.jpa.show-sql=true
spring.datasource.tomcat.validation-interval=30000
spring.datasource.tomcat.max-active=40
spring.datasource.tomcat.validation-query=select 1
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.test-while-idle=true
mybatis.type-aliases-package=com.wangcongming.shop.score.entity

3、添加mapper扫描

有两种方式,一种在启动类添加注解@MapperScan("com.wangcongming.shop.score.dao") 指定mapper所在的包,第二种是在每个mapper上使用注解@Mapper标注

二、注解使用

使用注解开发时,不需要再配置mapper.xml配置文件,具体示例如下:

  • 查询select
@Select("select * from score_detail where uid = #{uid}")
public ScoreDetail findScoreDetailByUid(String uid);
  • 更新update
@Update("update score_detail set type = #{type} where uid = #{uid}")
public void update(String uid,String type);
  • 插入insert
@Insert("insert into score_detail (id,uid,score,type) values(#{id},#{uid},#{score},#{type})")
public void insert(ScoreDetail entity);
  • 删除delete
@Delete("DELETE FROM score_detail where uid = #{uid}")
public void delete(String uid);

以上注解就实现了最基本的基于注解的mybatis开发,但是还存在一些问题。

  • 问题一:在查询时,数据中的字段可能和实体类中的字段不一致,那么就无法一一映射了。

在xml配置中是通过

<resultMap type="xxxx" id="xxxx">
        <result property="xxx" column="xxx"/>
        <result property="xxx" column="xxx"/>       
</resultMap>

进行映射,注解开发中也有与之对应的注解@Results和@Result,具体使用如下

 
@Select("select * from score_detail where uid = #{uid}")
@Results(
	{
		@Result(property = "uid",column = "uid"),
		@Result(property = "type",column = "type")
	}
)
public ScoreDetail findScoreDetailByUid(String uid);

其中property代表的是实体类属性,column代表的是表字段名

除了上述方法进行映射以外,也可以采用原来的xml配置映射,使用注解@ResultMap来进行指明即可。

另外如果不想采用以上方法,还可以通过给表中的查询字段取别名的方式来解决这个问题。

 

  • 问题二:如果是非常复杂的sql或者想要动态执行某个sql怎么解决

针对这个问题,mybatis还提供了注解@InsertProvider@UpdateProvider@DeleteProvider@SelectProvider来解决这个问题,简单举个例子说明一下。

@SelectProvider(type = ContentProvider.class,method = "findContentsSql")
public List<Content> findContents(int pageSize,long start,String type,String orderBy);

示例中type用来指明一个类,这个类里面写sql,method用来指明对应提供sql的方法名,具体示例如下:

/**
 *
 * @param pageSize
 * @param start
 * @param type
 * @param orderBy 排序 1-时间排序 2-点赞数排序 3-浏览次数排序 4-热度
 * @return
 */
public String findContentsSql(int pageSize,long start,String type,String orderBy){
	SQL sql = findSql(false);
	sql.WHERE("c.type = #{type}");
	String order = "create_time desc ";
	switch (orderBy){
		case "1":
			break;
		case "2":
			order = "praise_count desc ";
			break;
		case "3":
			order = "show_views desc ";
			break;
		case "4":
			order = "hot desc ";
			break;
		default:
			log.info("无此排序类型:{}<<<<<<<<<<<<<<<<",orderBy);
			break;
	}
	order += "limit #{start},#{pageSize}";
	sql.ORDER_BY(order);
	return sql.toString();
}

private SQL findSql(boolean isContent){
	SQL sql = new SQL();
	sql.SELECT(this.columns(false));
	sql.SELECT(this.userColumns());
	sql.FROM("nd_content c");
	sql.FROM("mb_user u");
	sql.WHERE("c.publishId = u.uid");
	sql.WHERE("c.status = '1'");
	sql.WHERE("c.open_flag = '0'");
	sql.WHERE("c.del_flag = '1'");
	return sql;
}

 

使用类来提供sql有很多好处,一来可以动态的加载sql,二来可以很好的利用java的继承等属性,从而实现代码复用

 

三、其他注解

以上提到的注解在开发中基本已经够用了,除此之外还有一些其他注解,如下:

 

具体的可以参考官方文档。

 

四、使用过程中的坑

使用@SelectProvider开发时,多参数传递时,必须使用@Param("uid")标注,同时Provider类中的方法也要使用@Param("uid")标注否则将无法匹配到参数。

 

参考博客: https://www.cnblogs.com/EasonJim/p/7070820.html

 

分享一套spring boot 学习视频:https://download.csdn.net/download/linhui258/10546450

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值