mybatis注解的详细使用(一对一,一对多详细解释带代码)

mac2025-12-30  7

1. @Results与 @Result的使用

@Result是最简单的映射,指定@Resul将基本数据库表字段,装配到实体类属性的映射。

column是数据库表的列名

property实体的字段

举例说明:

实体字段 表的列名 sid stuid sname stuname gid gid grade grade

对应的接口映射

@Results({ @Result(column="stuid",property="sid"), @Result(column="stuname",property="sname") }) @Select("select * from student where gid=#{aa}") public List<Student> queryStudentByGid(@param("aa")int aa);

(如:该方法中表中数据的返回类型就是根据list中的Student来决定的)

id、result语句属性配置细节:

2. @One(association联合)

联合元素用来处理“一对一”的关系。

两个属性:

select: 执行一个其它映射的SQL 语句返回一个Java实体类型。较灵活;fetchType会覆盖全局的配置参数lazyLoadingEnabled.

注意:select=指定查询语句,如果查询语句在其他的namespace中,则需要写全namespace.方法id

需求:在获取某个学生的信息的同时又想获取所属班级的所有信息

学生实体类:

public class Student { private Integer sid;//学生id private String sname; //学生姓名 private Integer gid; //班级id private Grade grade; //所属班级的所有信息 }

班级实体类:

public class Grade { private Integer id;//班级id private String gname;//班级名称 }

解释:在Student的字段中,Grade班级实体,需要查询班级表才能获取,学生表中没有该列(所以需要使用多表查询中,一对一关系,的 @Result中的one属性 和@One注解)

接口:

@Results({ //因为表中的字段与实体中的不同,所以使用了这两个注解,将表的列与实体的属性相对应 @Result(column="stuid",property="sid"), @Result(column="stuname",property="sname"), //因为实体中还有一个班级实体属性,但表中没有该字段,所以就要用多表查询 @Result(column="gid",property="grade",one=@One(select="cn.et.GradeAnnotationInterface.gradeInStudent"))}) //这里的property是实体中的字段,而column=gid就相当于关联的条件(也就是这个表的外键), //而select就是该关联条件对应的查询方法(通过包名全路径进行查找的) @Select("select * from student") public List<Student> queryAllStudent(); 注意: //在namespace="cn.et.GradeAnnotationInterface“下的方法 @Results(@Result(property="id",column="gid")) @Select("select * from grade where gid=#{aa}") public Grade gradeInStudent(@param("aa")int aa);

因为注解中已经指定了多表查询所以当调用指定了该注解的方法时多表查询的值会自动装配到对应的要返回实体属性中

如果上边的代码转换为普通的sql语句:

select s.*,g.*from student s inner join grade g ons.gid=g.gid

3. @Many注解( collection聚集)

联合元素用来处理“一对多”的关系。

两个属性同上的one一对一

需求:一个班级有多个学生(一对多)

学生实体字段:

public class Student { private Integer sid;//学生id private String sname; //学生姓名 private Integer gid; //班级id }

班级实体的字段:

public class Grade { private Integer id;//班级id private String gname;//班级名称 private List<Student> students;//该班级下所有的学生 }

解析:在Grade实体中有个List students属性,需要查询学生表才能获取,班级表中没有该信息(所以要使用多表查询一对多关系的, @Result中的many属性 和@Many注解)

@Results({ //因为表中的字段与实体中的不同,所以使用了这个注解,将表的列与实体的属性对应 @Result(property="id",column="gid"), //因为实体中还有一个学生List实体属性,但表中没有该字段,所以就要用多表查询来填充其中的值 @Result(property="students",column="gid",many=@Many(select="cn.et.StudentAnnotationInterface.queryStudentByGid"))}) //这里面property对应的是存放学生信息List的属性名,column对应的是班级表和学生表进行连接的字段(外键,从表进行连接的字段) //也可以这样来说(这里的property是实体中的字段,而column=gid就相当于关联的条件了而select就是该关联条件对应的查询方法) @Select("select * from grade") public List<Grade> queryAllGrade(); //在namespace="cn.et.annotation.StudentAnnotationInterface"下的查询语句和类型 @Results({ @Result(column="stuid",property="sid"), @Result(column="stuname",property="sname") }) @Select("select * from student where gid=#{0}") public List<Student> queryStudentByGid();
最新回复(0)