mybatis的一对多双向映射

mac2022-06-30  22

连表查询 select id resultType resultMap resultType和resultMap不能同时使用

association 属性 映射到多对一中的“一”方的“复杂类型”属性,例如javabean user对象中嵌套一个复杂类型属性 property 映射数据列的实体类属性 这里就是role javaType 完整java类名或者别名 resultMap 引用外面的resultMap association 子元素 id 主键id result 映射到javabean的某个“简单类型”的属性 property 映射数据列的实体类属性 column 数据库表字段或者别名 collection属性 映射到一对多中的“多”方的“复杂类型”属性,例如集合 role对象中嵌套一个复杂类型属性 property 映射数据列的实体类属性 这里就是user ofType 完整java类名或者别名 resultMap 引用外面的resultMap

多对一 “一”方实体类:public class User {

private Integer id; private String userName; private String userPassword; //创建一个角色对象 作用是查看用户信息同时还要看角色信息 private Role role;

省略getter和setter方法}sql映射文件:<mapper namespace="com.y2196.dao.UserMapper"> <resultMap type="com.y2196.entity.User" id="user"> <id property="id" column="id"/> <result property="userName" column="userName"/> <result property="userPassword" column="userPassword"/> <!-- 多对一 “一”方 要使用association来映射--> <association property="role" javaType="com.y2196.entity.Role"> <!-- 当有字段名相同的时候,要使用别名方式来区分 --> <id property="id" column="rid"/> <result property="roleName" column="roleName"/> </association> </resultMap> <!-- select标签 resultType和resultMap不能同时使用 --> <select id="findUserList" resultMap="user"> SELECT u.*,r.id AS rid,r.roleName FROM `user` u INNER JOIN role r ON u.roleId = r.id </select> </mapper>

一对多 “多”方 实体类: public class Role {

private Integer id; private String roleName; private List<User> userList; 省略getter和setter方法}sql映射文件:<resultMap type="com.y2196.entity.Role" id="role"> <!-- 当有字段名相同的时候,要使用别名方式来区分 --> <id property="id" column="rid"/> <result property="roleName" column="roleName"/> <collection property="userList" ofType="com.y2196.entity.User" resultMap="user"/></resultMap>

<select id="findRoleList" resultMap="role"> SELECT u.*,r.id AS rid,r.roleName FROM `user` u INNER JOIN role r ON u.roleId = r.id</select>

 

转载于:https://www.cnblogs.com/zhuhuibiao/p/9825318.html

最新回复(0)