mybatis 一对一和一对多的association collection

比如有个医药代表,需要查询其管理的医院、医院里对应医药代表的医生数以及医生的ID

实体类如下:其他省略

public class AgentVo{
	
	/**
	 * 医药代表
	 */
	private String agentId;

	/**
	 * 医院ID
	 */
    private Integer hospitalId;

    /**
     * 医院名称
     */
    private String hospitalName;

    /**
     * 医院对应的医生数
     */
	private Integer count;

	/**
	 * 医院对应的医生的ID
	 */
	private List<Integer> doctorIds;
	
}

mapper.xml文件设置:

<resultMap id="AgentVoMap" type="com.imlim.vo.AgentVo" >
  	<result column="agent_id" property="agentId" jdbcType="VARCHAR" />
    <result column="hospital_id" property="hospitalId" jdbcType="INTEGER" />
    <result column="hospital_name" property="hospitalName" jdbcType="VARCHAR" />
    <association property="count" column="{agentId=agent_id,hospitalId=hospital_id}" select="selectDoctorCount"></association>
  	<collection property="doctorIds" column="{agentId=agent_id,hospitalId=hospital_id}" select="selectDoctorIds"></collection>
  </resultMap>

  <select id="selectDoctorCount" resultType="java.lang.Integer">
  	select count(1) from t_doctor_relation_agent
  	where agent_id = #{agentId,jdbcType=VARCHAR}
  	and hospital_id = #{hospitalId,jdbcType=INTEGER}
  </select>
  
  <select id="selectDoctorIds" resultType="java.lang.Integer">
  	select doctor_id from t_doctor_relation_agent
  	where agent_id = #{agentId,jdbcType=VARCHAR}
  	and hospital_id = #{hospitalId,jdbcType=INTEGER}
  </select>
  
  <select id="get" resultMap="AgentVoMap">
  	SELECT
		agent.agent_id,
		agent.hospital_id,
		agent.hospital_name
	FROM
		t_doctor_relation_agent agent
	WHERE agent.agent_id = 15011
	GROUP BY
		agent.hospital_id
  </select>

测试结果:

[AgentVo [agentId=15011, hospitalId=1000, hospitalName=贵阳中医学院第一附属医院, count=1, doctorIds=[572]], AgentVo [agentId=15011, hospitalId=7720, hospitalName=测试一下, count=1, doctorIds=[571]], AgentVo [agentId=15011, hospitalId=7815, hospitalName=中文乱码2, count=2, doctorIds=[605, 606]], AgentVo [agentId=15011, hospitalId=7817, hospitalName=北京儿童医院111, count=2, doctorIds=[696, 47]]]

 

转载于:https://my.oschina.net/imlim/blog/1940524

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值