一、创建数据库 SQL
CREATE TABLE father (fatherId INT, fatherName VARCHAR(20), fatherAge INT);
CREATE TABLE son (sonId INT, fId INT, sonName VARCHAR(20), sonAge INT);
二、创建与数据库表对应的实体类
public class Father implements Serializable {
private int fatherId;
private String fatherName;
private int fatherAge;
private List<Son> sonList;
...
}
public class Son implements Serializable {
private int sonId;
private int fId;
private String sonName;
private int sonAge;
...
}
三、持久层接口
public interface IFatherDao {
List<Father> findAll();
}
public interface ISonDao {
Son findById(int id);
}
四、持久层映射文件
IFatherDao.xml
<mapper namespace="chu.yi.bo.dao.IFatherDao">
<resultMap id="fatherMap" type="chu.yi.bo.domain.Father">
<id column="fatherId" property="fatherId"/>
<result column="fatherName" property="fatherName"/>
<result column="fatherAge" property="fatherAge"/>
<collection property="sonList" ofType="chu.yi.bo.domain.Son"
select="chu.yi.bo.dao.ISonDao.findById"
column="fatherId"/>
</resultMap>
<select id="findAll" resultMap="fatherMap">
select * from father;
</select>
</mapper>
ISonDao.xml
<mapper namespace="chu.yi.bo.dao.ISonDao">
<select id="findById" resultType="chu.yi.bo.domain.Son" parameterType="int">
select * from son where fId = #{fatherId}
</select>
</mapper>
五、测试
List<Father> fatherList = iFatherDao.findAll();