自定义SQL的方式

  1. Annotation注解方式

  2. XML配置文件方式

Annotation注解方式

直接先定义接口方法,然后在接口方法上面开发注解即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.ledao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ledao.entity.BlogType;
import org.apache.ibatis.annotations.Select;

/**
* @author LeDao
* @company
* @create 2021-07-22 22:15
*/
public interface BlogTypeMapper extends BaseMapper {

/**
* 根据id查找博客类型
*
* @param id
* @return
*/
@Select("select * from t_blogtype where id=#{id}")
BlogType findById(Integer id);
}

XML配置文件方式

1、修改application.yml配置文件

1
2
3
4
mybatis-plus:
# 如果是放在src/main/java目录下 classpath:/com/*/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/**.xml
mapper-locations: classpath:/mapper/**.xml

2、自定义接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ledao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ledao.entity.BlogType;

import java.util.List;
import java.util.Map;

/**
* @author LeDao
* @company
* @create 2021-07-22 22:15
*/
public interface BlogTypeMapper extends BaseMapper<BlogType> {

/**
* 根据情况获取博客类型列表
*
* @param map
* @return
*/
List<BlogType> list(Map<String, Object> map);
}

3、xml文件实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ledao.mapper.BlogTypeMapper">
<resultMap id="BlogResult" type="com.ledao.entity.BlogType">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="sortNum" column="sortNum"/>
</resultMap>

<select id="list" parameterType="map" resultMap="BlogResult">
select *
from t_blogtype
<where>
<if test="name != null and name != ''">
and name like #{name}
</if>
</where>
<if test="start != null and size != null">
limit #{start},#{size}
</if>
</select>
</mapper>

4、测试代码

1
2
3
4
5
6
7
8
9
@Test
void list(){
Map<String, Object> map = new HashMap<>(16);
map.put("name", "%a%");
List<BlogType> blogTypeList = blogTypeMapper.list(map);
for (BlogType blogType : blogTypeList) {
System.out.println(blogType.getId() + "," + blogType.getName() + "," + blogType.getSortNum());
}
}

5、结果

img

PS.

来源:https://www.jianshu.com/p/c0dd01a82fcc