Mybatis-技术专区-如何清晰的解决出现「多对一模型」和「一对多模型」的问题
作者:互联网
基础使用篇
一对一
association
association通常用来映射一对一的关系,例如,有个类user,对应的实体类如下:
@Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) public class Student { private int id; private String name; /** * 学生要关联一个老师 */ private Teacher teacher; } @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) public class Teacher { private int id; private String name; }
Dao层进行Mapper查询操作
public interface TeacherMapper { Teacher getTeacher(@Param("tid") int id); Teacher getTeacher2(@Param("tid") int id); }
Dao层进行Mapper.xml文件
<resultMap id="StudentTeacher" type="com.sunreal.pojo.Student"> <result column="id" property="id"></result> <result column="name" property="name"></result> <association property="teacher" column="id" javaType="com.sunreal.pojo.Teacher" select="getTeacher"/> </resultMap> <select id="getStudent" resultMap="StudentTeacher"> select * from student </select> <select id="getTeacher" resultType="com.sunreal.pojo.Teacher"> select * from teacher where id = #{id} </select> <resultMap id="StudentTeacher2" type="com.sunreal.pojo.Student"> <result column="sid" property="id"></result> <result column="sname" property="name"></result> <association property="teacher" javaType="com.sunreal.pojo.Teacher"> <result property="name" column="tname"></result> </association> </resultMap> <select id="getStudent2" resultMap="StudentTeacher2"> select s.id sid, s.name sname, t.name tname from student s, teacher t where s.tid = t.id </select>
assocication:可以指定联合的JavaBean对象
- select:指定相关查询结果sqlid
- property="role“:指定哪个属性是联合的对象
- javaType:指定这个属性对象的类型
- column="{javabean熟悉=数据库字段,Javabean属性=数据库字段}"
<association property="role" javaType="com.queen.mybatis.bean.Role"> <id column="role_id" property="id"/> <result column="roleName" property="roleName"/> </association>
以上如果跨越命名空间的情况下:select:需要用namespace.selectId进行指定。
https://www.cnblogs.com/liboware/p/15220433.html
标签:专区,name,int,模型,private,Teacher,Mybatis,id,select 来源: https://www.cnblogs.com/luweiweicode/p/15224366.html