一、创建数据库 SQL
CREATE TABLE husband (husbandId INT, husbandName VARCHAR(20), husbandAge INT);
CREATE TABLE wife (wifeId INT, hId INT, wifeName VARCHAR(20), wifeAge INT);
二、创建与数据库表对应的实体类
public class Wife implements Serializable {
private int wifeId;
private int hId;
private String wifeName;
private int wifeAge;
private Husband husband;
...
}
public class Husband implements Serializable {
private int husbandId;
private String husbandName;
private int husbandAge;
...
}
三、持久层接口
public interface IWifeDao {
List<Wife> findAll();
}
public interface IHusbandDao {
Husband findById(int id);
}
四、持久层映射文件
IWifeDao.xml
<mapper namespace="chu.yi.bo.dao.IWifeDao">
<resultMap type="chu.yi.bo.domain.Wife" id="wifeMap">
<id column="wifeId" property="wifeId"/>
<result column="hId" property="hId"/>
<result column="wifeName" property="wifeName"/>
<result column="wifeAge" property="wifeAge"/>
<association property="husband" javaType="chu.yi.bo.domain.Husband"
select="chu.yi.bo.dao.IHusbandDao.findById"
column="hId"/>
</resultMap>
<select id="findAll" resultMap="wifeMap">
select * from wife;
</select>
</mapper>
IHusbandDao.xml
<mapper namespace="chu.yi.bo.dao.IHusbandDao">
<select id="findById" resultType="chu.yi.bo.domain.Husband" parameterType="int">
select * from husband where husbandId = #{hid}
</select>
</mapper>
五、测试
List<Wife> wifeList = wifeDao.findAll();