MyBatis 一对多映射配置

来源:互联网 发布:java 多线程并发 编辑:程序博客网 时间:2024/06/04 19:10

一个user有多个friend,在friend中有外键userId,引用到了user表中的userId

public class User {

private int userId;
private String userName;
private String password;
private int addr;//外键
private Address address;
private List<Friends> list;//一对多的集合用来存放多的数据

public List<Friends> getList() {
return list;
}
public void setList(List<Friends> list) {
this.list = list;

}

getter/setter方法

public class Friends {
private int friendId;
private String friendName;
private int userId;//外键

public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}

getter/setter方法

在user的映射文件中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"     
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.dao.UserDao">
<!-- 1:n select -->
<select id="onetomany" resultMap="rsid" parameterType="int">

select * from user u ,friend f where u.userId=f.userId and u.userId=#{uid}
</select>

<resultMap type="User" id="rsid">
<!-- user对象的基本属性映射 -->
<id property="userId" column="userid"/>
<result column="username" property="userName"/>
<result column="password" property="password"/>
<!-- 1:n -->
<!-- oftype指定list的类型 -->
<collection property="list" ofType="Friends">
<id property="friendId" column="friendId"/>
<result column="friendName" property="friendName"/>
</collection>
</resultMap>
</mapper>


0 0