MP、MybatisPlus、联表查询、自定义sql、Constants.WRAPPER、ew (一)
MP、MybatisPlus、联表查询、Constants.WRAPPER、ew
·
需求: 查询 `animal `表姓名像“狗”的同学的姓名、年龄、班级名称(从`class_table`中获取,其中`class_table`.id = `animal`.id)
Mapper层:
/**
* String WRAPPER = "ew";
* @param wrapper
* @return
*/
List<Animal> selectAnimals(@Param(Constants.WRAPPER) Wrapper<Animal> wrapper);
selectAnimals方法的xml:
<select id="selectAnimals" resultType="com.zhang.entity.Animal">
SELECT animal.`name`,animal.`age`,ct.`class_name`
FROM `animal` animal LEFT JOIN `class_table` AS ct
ON animal.`class_id` = ct.`id`
<where>
${ew.sqlSegment}
</where>
</select>
注意:此处要使用where标签,当wrapper条件复杂的时候,避免发生奇怪的问题。
测试:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class Test {
@Resource
private AnimalMapper animalMapper;
@org.junit.Test
public void test() {
String name = "狗";
QueryWrapper<Animal> wrapper = new QueryWrapper<>();
wrapper.like("animal.name", name);
animalMapper.selectAnimals(wrapper).forEach(System.out::println);
}
}
查询结果:

控制台打印SQL:
SELECT
animal.`name`,
animal.`age`,
ct.`class_name`
FROM
`animal` animal
LEFT JOIN `class_table` AS ct ON animal.`class_id` = ct.`id`
WHERE
(animal.NAME LIKE ?)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)