@Mapper
public interface UserMapper {
}
@Select("select * from t_user")
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
List<User> list();
/**
* 延伸:无论什么方式,如果涉及多个参数,则必须加上@Param注解,否则无法使用EL表达式获取参数。
*/
@Select("select * from t_user where username like #{username} and password like #{password}")
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
User get(@Param("username") String username, @Param("password") String password);
@SelectProvider
@InsertProvider
@UpdateProvider
@DeleteProvider
public class UserSqlProvider {
/**
* 方式1:在工具类的方法里,可以自己手工编写SQL。
*/
public String listByUsername(String username) {
return "select * from t_user where username =#{username}";
}
}
/**
* 方式2:使用注解指定某个工具类的方法来动态编写SQL.
*/
@SelectProvider(type = UserSqlProvider.class, method = "listByUsername")
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
List<User> listByUsername(String username);
@GetMapping("list/{username}")
public List<User> listByUsername(@PathVariable("username") String username) {
return userMapper.listByUsername(username);
}
UserSqlProvider.java
/**
* 方式2:也可以根据官方提供的API来编写动态SQL。
*/
public String getBadUser(@Param("username") String username, @Param("password") String password) {
return new SQL() {
{
SELECT("*");
FROM("t_user");
if (username != null && password != null) {
WHERE("username like #{username} and password like #{password}");
} else {
WHERE("1=2");
}
}}.toString();
}
UserMapper.java
@SelectProvider(type = UserSqlProvider.class, method = "getBadUser")
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
User getBadUser(@Param("username") String username, @Param("password") String password);
UserController.java
@GetMapping("get/bad/{username}/{password}")
public User getBadUser(@PathVariable("username") String username, @PathVariable("password") String password) {
return userMapper.getBadUser(username, password);
}