一、一对一映射:
1、先在数据库里边建两张表,学生表和地址表(规定一个学生只能有一个家庭地址,一个家庭地址只能对应一个学生),并插入一些数据信息;
2、在sts中创建实体类,Student和Address,并且Student中有一个Address属性;
3、创建映射接口StudentMapper,创建查询数据的方法;
public interface StudentMapper {
//查询所有学生,地址
List<Student> findStudentsWithAddress();
}
4、在映射文件里面进行对映射接口的配置;
(1)嵌套结果(把所有的sql语句都写在一起,即执行sql语句时只执行一句sql语句,把执行结果嵌套在一起):
<resultMap id="findStudentsWithAddressResult" type="com.briup.oneToone.Student">
<id property="studId" column="id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
<result property="phone" column="phone"/>
<association property="address" resultMap="AddressResult"></association>
</resultMap>
<resultMap id="AddressResult" type="com.briup.oneToone.Address">
<id property="addrId" column="addr_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
<result property="state" column="state"/>
<result property="zip" column="zip"/>
<result property="country" column="country"/>
</resultMap>
<!-- List<Student> findStudentsWithAddress(); -->
<select id="findStudentsWithAddress" resultMap="findStudentsWithAddressResult">
select s.id,s.name,s.email,s.dob,s.phone,
a.addr_id,a.street,a.city,a.state,a.zip,a.country
from students s left join addresses a
on s.addr_id=a.addr_id
</select>
(2)嵌套查询