1创建两张表
2创建持久化类
即对表中的字段创建JavaBean
映射文件
1.mybatis-config.xml文件中打开延时加载
<settings>
<setting name="logImpl" value="log4j" />
<!-- 懒加载设置为 true -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 积极加载设置为false -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
2.mapper文件
为每一张表创建一个对应的mapper.xml文件
IdcardMapper.xml
<mapper namespace="com.dao.IdCardDao">
<select id="selectCodeById" parameterType="Integer" resultType="com.po.Idcard">
select * from idcard where id = #{id}
</select>
</mapper>
PersonMapper.xml
<mapper namespace="com.dao.PersonDao">
<!-- 一对一根据id查询个人信息:级联查询的第一种方法(嵌套查询,执行两个sql语句) -->
<resultMap type="com.po.Person" id="cardAndPerson1">
<!-- property是 com.po.Person中的属性-->
<!-- column是查询结果的列名,可以来自不同的表 -->
<id property="id" column="id"/><!-- id标签用于表示哪个列是主键 -->
<result property="name" column="name"/> <!-- 注入到字段或者JavaBean属性的普通结果 -->
<result property="age" column="age"/>
<!-- 一对一级联查询 -->
<association property="card" column="idcard_id" javaType="com.jilian.po.Idcard"
select="com.dao.IdCardDao.selectCodeById"/><!-- 用于一对一关联 -->
</resultMap>
<select id="selectPersonById1" parameterType="Integer" resultMap="cardAndPerson1">
select * from person where id = #{id}
</select>
</mapper>
创建数据库接口
(使用@Repository和@Mapper注解)
创建dao包,在包中创建映射文件对应的数据库操作接口
调用接口方法
(@Controller注解)
创建测试类
public class TestOneToOne {
public static void main(String[] args) {
ApplicationContext appcon = new ClassPathXmlApplicationContext("applicationContext.xml");
OneToOneController oto = (OneToOneController) appcon.getBean("oneToOneController");
oto.test();
}
}
在Mapper文件中
使用连接查询
<!-- 一对一 根据id查询个人信息: 连接查询(使用POJO储存结果) -->
<select id="selectPersonById3" parameterType="Integer" resultType="com.jilian.pojo.SelectPersonById">
select p.*,ic.code from person p,idcard ic
where p.idcard_id = ic.id and p.id = #{id}
</select>
创建POPJ类(将需要查询的列写成一个javabean文件)
在这里插入代码片