Mybatis中使用Association元素进行一对一级联查询

本文介绍了在Mybatis中如何使用Association元素处理一对一映射关系,以查询员工及其对应的部门为例,详细解析了column、property、javaType、jdbcType等属性的设置和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   Association元素处理“一对一”类型映射关系,例如,查询有员工所对应的部门,它需要指定column、property、javaType、jdbcType等属性,如下:

<association property="javaben字段" javaType="javabaen所在的类名">
    <id column="表字段" property="javabean字段"/>
    <result column="表字段" property="javabean字段"/>
</association>
Association元素属性:



1.数据表

t_dept:


t_user:


2.employe.java

package com.casv.model;

public class employee {

	private int uid;
	private String name;
	private String pwd;
	private department dept;//部门实体类

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public department getDept() {
		return dept;
	}

	public void setDept(department dept) {
		this.dept = dept;
	}

}
3.userMapper.java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper SYSTEM "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- namespace:命名空间,对应dao接口 --> 
<mapper namespace="com.casv.dao.userMapper">
	<!-- 配置resultMap属性,进行表字段与实体类属性映射 -->
	<resultMap id="BaseResultMap" type="emps">
		<id column="u_id" property="uid"></id>
		<result column="u_name" property="name"></result>
		<result column="u_pwd" property="pwd"></result>
		<association property="dept" javaType="depts">
		    <id column="p_id" property="pid"/>
		    <result column="p_name" property="pname"/>
		</association>
	</resultMap>
	<!-- 多表查询操作  -->
	<select id="selectemp" parameterType="int" resultMap="BaseResultMap">
	   select * from t_user u inner join t_dept d where u.p_id=d.p_id and u.u_id=#{id}
	</select>
</mapper>
4.test测试类

public void testdeptbyemp(){
      session=MyBatisUtil.getSessionFactory().openSession();
      emp=session.selectOne("com.casv.dao.userMapper.selectemp",1);
      System.out.println(emp.getUid()+" "+emp.getName()+" "+emp.getPwd()+" "+emp.getDept().getPname());
}
运行结果:
1 etccbw 123456 技术部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值