Mybatis- 高级
注解开发
单表查询
-
常用注解
- @Select(“查询的 SQL 语句”):执行查询操作注解
- @Insert(“新增的 SQL 语句”):执行新增操作注解
- @Update(“修改的 SQL 语句”):执行修改操作注解
- @Delete(“删除的 SQL 语句”):执行删除操作注解
-
配置核心配置文件
<mappers> <package name="接口所在包"/> </mappers>
多表查询
一对一
-
@Results:封装映射关系的父注解。 Result[] value():定义了 Result 数组
-
@Result:封装映射关系的子注解。 column 属性:查询出的表中字段名称 property 属性:实体对象中的属性名称 javaType 属性:被包含对象的数据类型 one 属性:一对一查询固定属性
-
@One:一对一查询的注解。 select 属性:指定调用某个接口中的方法
public interface CardMapper {
@Select("select * from card")//select注解- 查找card 表中所有数据
@Results({
@Result(column = "id", property = "id"),//给card类中成员变量赋值
@Result(column = "number", property = "number"),
@Result(//给Card 中包含的实体类赋值
property = "p", //property 属性 表示该实体类变量名
javaType = Person.class, // javatype 属性表示该实体类的具体数据类型
column = "pid", //g根据查询出来的card中的pid字段来查询person表
//一对一查询的固定写法 select属性值表示调用哪个接口中的哪个方法
one = @One(select = "OneToOne.PersonMapper.selectAll")
)
})
List<Card> selectAll();
}
public interface PersonMapper {
//查询全部
@Select("select * from student where id=#{id}")
public abstract Person selectAll(Integer id);
}
一对多
public interface ClassMapper {
//查询全部
@Select("select * from classes")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "name", property = "name"),
@Result(
property = "students", // 被包装对象的变量名
javaType = List.class, // 被包装对象实际参数类型
column = "id", //用classes表中查询出来的id来查询student表
many = @Many(select = "OneToMany.StudentMapper.selectById")
)
})
public abstract List<Classes> selectAll();
}
public interface StudentMapper {
@Select("select * from student where cid=#{cid}")
List<Student> selectByCid(Integer id);
}
SQL构建器的使用
- 成员代码块
new SQL(){
{
SELECT("*");
FROM("student");
} // 成员代码块儿, 构造代码块儿
};
//@Select("SELECT * FROM student")
@SelectProvider(type = ReturnSql.class , method = "getSelectAll")
public abstract List<Student> selectAll()
- @SelectProvider
- type: 指定提供SQL的功能类
- method: 指定调用功能类的哪一个方法
SQL构建器使用步骤
- 构建SQL构建类
- 编写一方法,返回值为String
- 在原本注解开发的地方将原有的@XXX注解改为@XXProvider注解
- type参数指定构建类
- method指定对应sql的方法