mybatis 對象內包含對象如何查詢(一)

mybatis在進行查詢時,對象內的屬性是另外一種對象的數組java

一樣是用collection標籤,先介紹第一種,也是醉實用的方法,每次只要訪問一遍數據庫就能夠將結果所有出來而且幫你封裝好sql

主對象數據庫

public class ReachPrivilege {
	private List<ReachPrivilegeDetail> rpds;// 關聯對象的集合

	private Long rpId;

	private String rpName;

	private Long beginTime;

	private Long endTime;
//省略get和set方法
}

被關聯的對象數組

public class ReachPrivilegeDetail {
    private Long rpdId;

    private Long rpId;

    private Integer level;

    private Integer require;

    private Integer remissionCash;

    private Integer pinkage;

    private Integer sendPoint;

    private Integer universal;

    private Long couponId;
//省略get和set方法
}

xml的resultMap配置mybatis

<resultMap type="com.impression.model.ReachPrivilege" id="rpdsMap">
		<id column="rp_id" property="rpId" jdbcType="BIGINT" />
		<result column="rp_name" property="rpName" jdbcType="VARCHAR" />
		<result column="begin_time" property="beginTime" jdbcType="BIGINT" />
		<result column="end_time" property="endTime" jdbcType="BIGINT" />
         <!--  開始配置關聯屬性 -->
		<collection property="rpds" javaType="java.util.List"
			ofType="com.impression.model.ReachPrivilegeDetail">
			<id column="rpd_id" property="rpdId" jdbcType="BIGINT" />
			<result column="rpd_rp_id" property="rpId" jdbcType="BIGINT" />
			<result column="rpd_level" property="level" jdbcType="INTEGER" />
			<result column="rpd_require" property="require" jdbcType="INTEGER" />
			<result column="rpd_remission_cash" property="remissionCash"
				jdbcType="INTEGER" />
			<result column="rpd_pinkage" property="pinkage" jdbcType="INTEGER" />
			<result column="rpd_send_point" property="sendPoint" jdbcType="INTEGER" />
			<result column="rpd_universal" property="universal" jdbcType="INTEGER" />
			<result column="rpd_coupon_id" property="couponId" jdbcType="BIGINT" />
		</collection>
</resultMap>

注:這邊就關係到數據庫的列名規範了,之前我無所謂列名規範,自從用了這個我已經開始嚴格遵照規範了,對於這個提示,懂了也就懂了吧,不懂得等多踩點坑之後也會懂的ui

接下來教你如何寫sql進行查詢spa

<select id="queryAndRpdsByStatus" resultMap="rpdsMap">
		select
		a.rp_id, a.rp_name, a.begin_time, a.end_time,
		b.rpd_id as rpd_id,
		b.rp_id as rpd_rp_id,
		b.level as rpd_level,
		b.require as rpd_require,
		b.remission_cash as rpd_remission_cash,
		b.pinkage as rpd_pinkage,
		b.send_point as rpd_send_point,
		b.universal as rpd_universal,
		b.coupon_id as rpd_coupon_id
		from im_reach_privilege a
		left join
		im_reach_privilege_detail b
		on a.rp_id=b.rp_id
		where 1=1
		<if test=" status == 1">
			and a.begin_time &gt; #{time,jdbcType=BIGINT}
		</if>
		<if test=" status == 2">
			and a.begin_time &lt; #{time,jdbcType=BIGINT}
			and
			(a.end_time &gt; #{time,jdbcType=BIGINT}
			or a.end_time = 0)
		</if>
		<if test=" status == 3">
			and a.end_time &lt; #{time,jdbcType=BIGINT}
			and a.end_time
			!= 0
		</if>
	</select>

其實就是普通的左聯查詢語句,只不過之前用左聯查詢出來的結果是一片,如今mybatis幫你把數據分解好了,根據主對象的id將數據進行分割封裝好了給你code

相關文章
相關標籤/搜索