一些依赖关系
1、mybatis-spring-boot-starter 包含 spring-boot-starter-jdbc。
mybatis运行原理:
1、自动检测现有的DataSource;
2、创建 并注册SqlSessionFactory的实例,该实例使用 SqlSessionFactoryBean 将该DataSource 作为输入进行传递;
3、创建并注册从SqlSessionFactory中获得的SqlSessionTemplate的实例;
4、自动扫描mappers,将其链接到SqlSessionTemplate 并注册到SpringContext,以便注册到Bean中。
总的来说就是:使用了该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。
集成MyBatis
domain层、service层、controller层和用Jdbc都是一样的,只是dao层不一样:
注解方式实现
1、不需要dao接口,在创建daoImpl.java 实现dao接口;只需要创建Mapper接口即可。
2、在接口上添加@Mapper注解,或在入口类上添加:@MapperScan(“*.dao”)。那么问题来了,添加了@Mapper注解了,还需要添加@Component注解?
经测试,去掉@Component注解也是可以的。打开@Mapper的盖子看了看,发现@Component注解包含的东西它都有。所以理论上是可行的。
然后看了博主的注释,据说不加@Component,service层那里不是由@Autowire注入吗,所以会有错误提示,所以应该是“约定配置”层面的问题。
那么问题又来了,难道不应该@Repository吗??
上代码:
@Component
@Mapper
public interface LearnMapper {
@Insert("insert into learn_resource(author, title,url) values(#{author},#{title},#{url})")
int add(LearnResouce learnResouce);
@Update("update learn_resource set author=#{author},title=#{title},url=#{url} where id = #{id}")
int update(LearnResouce learnResouce);
@DeleteProvider(type = LearnSqlBuilder.class, method = "deleteByids")
int deleteByIds(@Param("ids") String[] ids);
@Select("select * from learn_resource where id = #{id}")
@Results(id = "learnMap", value = {
@Result(column = "id", property = "id", javaType = Long.class),
@Result(property = "author", column = "author", javaType = String.class),
@Result(property = "title", column = "title", javaType = String.class)
})
LearnResouce queryLearnResouceById(@Param("id") Long id);
@SelectProvider(type = LearnSqlBuilder.class, method = "queryLearnResouceByParams")
List<LearnResouce> queryLearnResouceList(Map<String, Object> params);
class LearnSqlBuilder {
public String queryLearnResouceByParams(final Map<String, Object> params) {
StringBuffer sql =new StringBuffer();
sql.append("select * from learn_resource where 1=1");
if(!StringUtil.isNull((String)params.get("author"))){
sql.append(" and author like '%").append((String)params.get("author")).append("%'");
}
if(!StringUtil.isNull((String)params.get("title"))){
sql.append(" and title like '%").append((String)params.get("title")).append("%'");
}
System.out.println("查询sql=="+sql.toString());
return sql.toString();
}
//删除的方法
public String deleteByids(@Param("ids") final String[] ids){
StringBuffer sql =new StringBuffer();
sql.append("DELETE FROM learn_resource WHERE id in(");
for (int i=0;i<ids.length;i++){
if(i==ids.length-1){
sql.append(ids[i]);
}else{
sql.append(ids[i]).append(",");
}
}
sql.append(")");
return sql.toString();
}
}
}
Tips:
简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可;
But,
复杂点需要动态SQL语句,就比如上面方法中根据查询条件是否有值来动态添加sql的,就需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。
Xml配置文件实现
修改application.properties 配置文件
#指定bean所在包
mybatis.type-aliases-package=com.dudu.domain
#指定映射文件
mybatis.mapperLocations=classpath:mapper/*.xml
然后请欣赏:Mapper.xml
<?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.dudu.dao.LearnMapper">
<resultMap id="baseResultMap" type="com.dudu.domain.LearnResouce">
<id column="id" property="id" jdbcType="BIGINT" />
<result column="author" property="author" jdbcType="VARCHAR"/>
<result column="title" property="title" jdbcType="VARCHAR"/>
<result column="url" property="url" jdbcType="VARCHAR"/>
</resultMap>
<sql id="baseColumnList" >
id, author, title,url
</sql>
<select id="queryLearnResouceList" resultMap="baseResultMap" parameterType="java.util.HashMap">
select
<include refid="baseColumnList" />
from learn_resource
<where>
1 = 1
<if test="author!= null and author !=''">
AND author like CONCAT(CONCAT('%',#{author,jdbcType=VARCHAR}),'%')
</if>
<if test="title != null and title !=''">
AND title like CONCAT(CONCAT('%',#{title,jdbcType=VARCHAR}),'%')
</if>
</where>
</select>
<select id="queryLearnResouceById" resultMap="baseResultMap" parameterType="java.lang.Long">
SELECT
<include refid="baseColumnList" />
FROM learn_resource
WHERE id = #{id}
</select>
<insert id="add" parameterType="com.dudu.domain.LearnResouce" >
INSERT INTO learn_resource (author, title,url) VALUES (#{author}, #{title}, #{url})
</insert>
<update id="update" parameterType="com.dudu.domain.LearnResouce" >
UPDATE learn_resource SET author = #{author},title = #{title},url = #{url} WHERE id = #{id}
</update>
<delete id="deleteByIds" parameterType="java.lang.String" >
DELETE FROM learn_resource WHERE id in
<foreach item="idItem" collection="array" open="(" separator="," close=")">
#{idItem}
</foreach>
</delete>
</mapper>
最后分页插件了解一下:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
只需在查询list之前使用PageHelper.startPage(int pageNum, int pageSize)方法即可。pageNum是第几页,pageSize是每页多少条。
@Override
public List<LearnResouce> queryLearnResouceList(Map<String,Object> params) {
PageHelper.startPage(Integer.parseInt(params.get("page").toString()), Integer.parseInt(params.get("rows").toString()));
return this.learnMapper.queryLearnResouceList(params);
}
?说的个JB啥啊…
分页插件PageHelper项目地址: https://github.com/pagehelper/Mybatis-PageHelper
Reference:
[1]: http://tengj.top/2017/04/23/springboot9/