就国内来说项目中mybatis使用的较多,因为方便灵活,上手快,会写sql就能用好mybatis,另外sql优化等简单易做,遇到慢sql了比hibernate更好排查。除了一大痛点,因为项目短平快,所以开发过程中大概率会出现发现某个表要加字段要删字段要改字段等头疼的事,你以为我会说,这么麻烦不想调么,不,不存在的。
言归正传,在查询里使用子查询是比较频繁的。这文章的下半部分就是要解决子查询一个对象,一个对象列表的问题,并且子查询中的条件除了关联字段还有其他的参数需要传入。
本示例中要查询的表结构如下:
此处的需求是要根据分组id(即geoId)查询stationVO对象
mybatis中对应的映射及代码如下:
<resultMap type="org.sit.cto.smmrepository.vo.StationVO"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="code" jdbcType="VARCHAR" property="code" /> <result column="status" jdbcType="INTEGER" property="status" /> <result column="label_id" jdbcType="BIGINT" property="labelId" /> <result column="esl_code1" jdbcType="VARCHAR" property="eslCode" /> <result column="lcode" jdbcType="VARCHAR" property="labelCode" /> <result column="geo_id" jdbcType="BIGINT" property="stationGeoId" /> <association property="employee" column="employee_id" select="selectEmployeeByEmployeeId"/> <collection property="bizList" column="{geoId=geo_id,eslCode=esl_code1}" ofType="map" select="selectBizVOByStationId"/> </resultMap> <resultMap type="org.sit.cto.smmrepository.model.Employee"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="code" jdbcType="VARCHAR" property="code" /> <result column="real_name" jdbcType="VARCHAR" property="realName" /> <result column="company" jdbcType="VARCHAR" property="company" /> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> <result column="position" jdbcType="VARCHAR" property="position" /> <result column="phone" jdbcType="VARCHAR" property="phone" /> <result column="status" jdbcType="INTEGER" property="status" /> </resultMap> <resultMap type="org.sit.cto.smmrepository.vo.BizVO"> <result column="esl_code" jdbcType="VARCHAR" property="eslCode" /> <result column="temp_id" jdbcType="BIGINT" property="labelTempId" /> <result column="key" jdbcType="VARCHAR" property="key" /> <result column="value" jdbcType="VARCHAR" property="value" /> </resultMap> <select resultMap="EmployeeResultMap"> select id, code, real_name, company, dept_name, position, phone, status from tb_employee where id=#{employeeId} </select> <select parameterType="java.util.Map" resultMap="BizVOResultMap"> select esl_code, temp_id, key, value from tb_biz where associated_id=#{geoId} and esl_code=#{eslCode} and biz_type=2 </select> <select resultMap="StationVOResultMap"> SELECT ts.ID, ts.code, ts.geo_id, ts.label_id, ts.employee_id, ts.status, tl.code lcode, tl.esl_code1 FROM tb_station ts LEFT JOIN tb_label tl ON ts.label_id = tl.ID WHERE ts.geo_id =#{geoId} ORDER BY ts.code </select>子查询获取一个关联对象
例子中的employee
子查询获取一个关联对象的集合
示例中Biz对象的集合
规范定义好resultmap,能让sql更有条理更美观