一对一级联查询

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文件)

在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值