一、引言 MP自带的条件构造器虽然很强大,有时候也避免不了写稍微复杂一点业务的sql,那么那么今天说说MP怎么自定义sql语句吧。
二、配置 自定义的sql当然是写在XML文件中的啦,那么首先来定义xml文件的位置,在yml配置文件如下
1 2 3 4 mybatis-plus: mapper-locations: classpath:/mapper/**.xml
三、具体实现 使用注解实现:
在我们Mapper接口中定义自定义方法即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public interface UserMapper extends BaseMapper <User> { @Select("SELECT * FROM user ${ew.customSqlSegment}") List<User> selectByMyWrapper (@Param(Constants.WRAPPER) Wrapper<User> userWrapper) ; @Select("SELECT * FROM user where name = #{name}") List<User> selectByName (@Param("name") String name) ; }
使用xml文件实现:
使用xml一定要指定xml文件所在位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public interface UserMapper extends BaseMapper <User> { List<User> selectByMyWrapper (@Param(Constants.WRAPPER) Wrapper<User> userWrapper) ; List<User> selectByName (@Param("name") String name) ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 <?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.example.demo.mapper.UserMapper" > <select id ="selectByName" resultType ="com.example.demo.model.User" > SELECT * FROM user where name = #{name} </select > <select id ="selectByMyWrapper" resultType ="com.example.demo.model.User" > SELECT * FROM user ${ew.customSqlSegment} </select > </mapper >
测试测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Test public void selectByMySelect () { List<User> users = userMapper.selectByName("王天风" ); users.forEach(System.out::println); } @Test public void selectByMyWrapper () { QueryWrapper<User> wrapper = new QueryWrapper (); wrapper.like("name" , "雨" ).lt("age" , 40 ); List<User> users = userMapper.selectByMyWrapper(wrapper); users.forEach(System.out::println); }
四、能否提供自定义Update语句与Wrapper的整合使用呢? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public interface UserMapper extends BaseMapper <User> { int updateByMyWrapper (@Param(Constants.WRAPPER) Wrapper<User> userWrapper, @Param("user") User user) ; }
1 2 3 4 5 6 7 8 9 <?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.example.demo.mapper.UserMapper" > <update id ="updateByMyWrapper" > UPDATE user SET email = #{user.email} ${ew.customSqlSegment} </update > </mapper >
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void updateByMyWrapper () { QueryWrapper<User> wrapper = new QueryWrapper (); wrapper.eq("name" , "admin" ); User user = new User (); user.setEmail("Test@email.com" ); userMapper.updateByMyWrapper(wrapper, user); }