Mybatis注解开发之动态SQL
Mybatis的开发方式其实有3种:
原始Dao开发(就是把mapper接口、映射文件和实现类都一并开发)
xml代理(就是只实现mapper接口和映射文件)
3.注解代理(就是只实现mapper接口,把映射文件的内容通过注解来写)
注解开发也分3种:
1.静态SQL
2.动态SQL
3.多表关联
主要注解有:
静态:
@Insert:相当于标签,实现新增 @Update: 相当于 标签,实现更新 @Delete: 相当于 标签,实现删除 @Select: 相当于标签,实现查询
多表关联:
@Results: 相当于标签,需要和@Result注解一起使用。 @Result: 相当于 和 标签,实现结果集中某一列的数据映射 column 数据库的列名 property 需要装配的属性名 one 需要使用的@One 注解(@Result(one=@One())) many 需要使用的@Many 注解(@Result(many=@many())) @One: 相当于 标签,实现一对一关系映射 @Many:相当于 标签,实现一对多关系映射 @One和@Many注解的属性: select 属性:代表将要执行的 sql 语句 fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
使用格式:
1.@Results({@Result(),@Result()})或@Results(@Result())
2.@Result(column=" ",property="",one=@One(select=""))
具体例子:
public interface AnnotationUserMapper {
// 查询
@Select("SELECT * FROM user WHERE id = #{id}")
public User findUserById(int id);
// 模糊查询用户列表
@Select("SELECT * FROM user WHERE username LIKE '%${value}%'")
public List findUserList(String username);
// 添加并实现主键返回
@Insert("INSERT INTO user (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})")
@SelectKey(before=false,statement="SELECT LAST_INSERT_ID()",keyProperty="id",resultType=int.class)
public void insertUser(User user);
// 动态SQL
@SelectProvider(type=UserSqlBuilder.class,method="getDynamicSQL")
public List dynamicSQL(UserQueryVO vo);
// 使用Results注解完成结果映射
@Results({
@Result(column="id",property="id"),
@Result(column="username",property="username"),
@Result(column="sex",property="sex"),
@Result(column="address",property="address")
})
@Select("SELECT * FROM user WHERE id = #{id}")
public User findUserByIdWithResultMap(int id);
// 演示延迟加载
@Results({
@Result(column="id",property="id"),
@Result(column="user_id",property="user_id"),
@Result(column="number",property="number"),
@Result(column="note",property="note"),
@Result(property="user",javaType=User.class,column="user_id",
one=@One(select="com.kkb.mybatis.anno.AnnotationUserMapper.findUserById",fetchType=FetchType.LAZY))
})
@Select("SELECT * FROM orders")
public List lazyLoading();
public class UserSqlBuilder {
public String getDynamicSQL(final UserQueryVO vo) {
return new SQL() {
{
SELECT("*");
FROM("user");
User user = vo.getUser();
if (user != null) {
if(user.getUsername() != null && !user.equals("")) {
WHERE("username like '%"+user.getUsername()+"%'");
}
}
ORDER_BY("id");
}
}.toString();
}
}
}

