Mybatis框架学习笔记 lesson2

来源:互联网 发布:2000w数据 在线查询 编辑:程序博客网 时间:2024/05/11 12:10

Mybatis 分页


封装相关数据成一个类

public class Page {

private int PageNo;                                页号

private int PageSize;                             每页数量

private int PageStart;                             起始页

private String orderByField;                 排序条件

private String orderByDescAndAsc;  升序降序

}


DeptMapper

  <select id="selectPage" resultType="d"  parameterType="page">
    select * from dept  order by #{orderByField} desc limit #{pageStart},#{pageSize}
   </select>


动态sql (条件查询)

在Page内添加查询条件属性

private Dept condition

DeptMapper

 <select id="selectPageBySql" resultType="d"  parameterType="page">

    select * from dept   

    <where>

    <iftest="condition!=null">

    <if test="condition.dname!=nulland condition.dname!=''">

         dname  like #{condition.dname}  

    </if>

     

    <if test="condition.loc!=null and condition.loc!=''">

          loc like   #{condition.loc}

    </if>

    </if>

    </where>

    order by #{orderByField} desc limit #{pageStart},#{pageSize}

   </select>


sql片段

  <sql id="myCondition1">

      <if test="condition!=null">

    <if test="condition.dname!=null and condition.dname!=''">

      and     dname  like #{condition.dname}   

    </if>

     

    <if test="condition.loc!=null and condition.loc!=''">

    and     loc like   #{condition.loc}

    </if>

    </if>

     </sql>

  需要sql片段的地方:

   <include refid="sql片段的id"> 

  <include refid="myCondition1"/>


多表查询下的mybatis配置

OneToOne

 <resultMap type="Order" id="mymap">

    <id property="id" column="oid"/>

    <result property="create_date" column="create_date"/>

    <result property="num" column="num"/>

    <result property="custom_id" column="custom_id"/>

    <!-- 配置一个订单属于一个客户的 -->

    <association property="custom"  javaType="custom">

      <id column="cid"  property="id"/>

      <result column="cname" property="cname"/>

      <result column="age" property="age"/>

    </association>

   </resultMap>

  

  <select id="selectOrderAndCustom2"  resultMap="mymap">

  SELECT o.id oid,o.create_date,o.num,o.custom_id, c.id cid,c.cname,c.age FROM  orders o, custom c

      WHERE o.custom_id=c.id

  </select>


OneToMany

<resultMap type="Dept" id="mymap2">

   <id column="dno" property="dno">

   <result column="dname"  property="dname">

   <result column="loc"  property="loc">

   <collectionproperty="emps"  ofType="Emp">

<id column="empno" property="empno"/>

<result column="ename"  property="ename">

.....

</collection>

0 0