1. 程式人生 > >Mybatis 實現2表關聯的各個條件實現查詢

Mybatis 實現2表關聯的各個條件實現查詢

mybatis:

<sql id="mColumns">
   m.id,
   m.maintainCode,
   m.maintainUserId,
   mu.id as mid,
   mu.name as uname,//m的實體裡有uname的屬性
   mu.licencePlate,
   mu.vin

</sql>

<resultMap id="getMt" type="Maintain">
   <result property="id" column="id"/>
   <result property="maintainCode" column="maintainCode"/>
   <result property="maintainUserId" column="maintainUserId"/>
   <association property="maintainUser" javaType="MaintainUser">
      <id property="id" column="mid"/>
      <result property="name" column="uname"/>
      <result property="licencePlate" column="licencePlate"/>
      <result property="vin" column="vin"/>
   </association>
</resultMap>


<select id="findList" resultMap="getMt">
   select
   <include refid="mColumns"/>
   FROM maintainuser mu
   join  `maintain` m on m.maintainUserId=mu.id
   where 1=1
   <if test="maintainCode!=null and maintainCode !=''">
      and m.maintainCode like CONCAT('%',#{maintainCode},'%')
   </if>
   <if test="uname !=null">
      and mu.name like CONCAT('%',#{uname},'%')
   </if>
</select>

實體類:

Maintain
private String id;
private String maintainCode; //維修單號
private MaintainUser maintainUser;
private String uname;
MaintainUser

private String id; private String name;//車主姓名

JSP頁面:

<div>
   <label>維修單號:</label><input name="maintainCode" type="text" value="${maintain.maintainCode}"/>
   <label>維修使用者:</label><input name="uname" type="text" value="${maintain.uname}"/>
   <input id="btnSubmit" type="submit" value="查詢"/>
</div>

效果圖: