mybatis中sql语句查询操作
动态sql
where if
where可以自动处理第一个and。
<!-- 根据id查询用户信息 -->
    <!-- public User findUserById(int id); -->
    <select id="findUserById" parameterType="user" resultType="user">
        select * from user 
        <!-- 当有if条件成立时,where会自动拼接查询条件,并处理第一个and -->
        <include refid="where_if_if"/>
    </select>
    <!-- sql片段抽取 -->
    <sql id="where_if_if">
        <where>
        <!-- 动态拼接sql查询条件 -->
            <if test="username != null and username != ">
                 and username like "%"#{username}"%"
            </if>
            <if test="sex != null and sex != ">
                and sex = #{sex}
            </if>
        </where>
    </sql> 
foreach
向sql传递数组或List,mybatis使用foreach解析
 在pojo中定义list属性ids存储多个用户id,并添加getter/setter方法
<select id="findUserByForeach" parameterType="queryvo" resultType="user">
        select * from user
        <if test="ids != null and ids.size > 0 ">
            <foreach collection="ids" item="id" open="where id in (" separator=", " close=")">
                #{id}
            </foreach>
        </if>
    </select> 
关联查询
一对一:
案例:查询所有订单信息,关联查询下单用户信息。
- 使用resultType,定义一个新的pojo,使其继承pojoA后包含了pojoA所有字段,在pojo中添加新的字段
- 使用resultMap,定义专门的resultMap用于映射一对一查询结果,在pojoA中加入属性
association:表示进行关联查询单条记录 property:表示关联查询的结果存储在cn.itcast.mybatis.po.Orders的user属性中 javaType:表示关联查询的结果类型 <id property="id" column="uid"/>:查询结果的uid列对应关联对象的id属性,这里是<id />表示uid是关联查询对象的唯一标识。 <result property="username" column="username"/>:查询结果的username列对应关联对象的username属性。
一对多:
案例:查询所有用户信息,同时关联查询用户的订单信息。
用户信息和订单信息为一对多关系。
- 在User类中加入List orders属性,同时添加get/set方法
collection部分定义了用户关联的订单信息。表示关联查询结果集 property="orders":关联查询的结果集存储在User对象的上哪个属性。 ofType="orders":指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名。 <id />及<result/>的意义同一对一查询。

