一、创建数据库 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 String wifeName;
private int wifeAge;
...
}
public class Husband implements Serializable {
private int husbandId;
private String husbandName;
private int husbandAge;
private Wife wife;
...
}
三、持久层接口
public interface IHusbandDao {
List<Husband> findAll();
}
四、持久层映射文件
<mapper namespace="chu.yi.bo.dao.IHusbandDao">
<resultMap id="husbandMap" type="chu.yi.bo.domain.Husband">
<id column="husbandId" property="husbandId"/>
<result column="husbandName" property="husbandName"/>
<result column="husbandAge" property="husbandAge"/>
<association property="wife" javaType="chu.yi.bo.domain.Wife">
<id column="wifeId" property="wifeId"/>
<result column="wifeName" property="wifeName"/>
<result column="wifeAge" property="wifeAge"/>
</association>
</resultMap>
<select id="findAll" resultMap="husbandMap">
select h.*,w.* from husband h,wife w where h.husbandId = w.hid;
</select>
</mapper>
五、测试
List<Husband> husbandList = husbandDao.findAll();