<select id="selByCondition" resultMap="rm">
select *
from mybatis
<where>
<if test="status !=null">
and STATUS=#{STATUS}
if>
<if test="companyName !=null and companyName !=''">
and company_name like #{companyName}
if>
<if test="bracdName !=null and bracdName !=''">
and bracd_name like #{bracdName}
if>
where>
select>
标签可以自动帮我们去掉and
<select id="selByCondition2" resultMap="rm">
select *
from mybatis where
<choose>
<when test="status !=null">
STATUS=#{STATUS}
when>
<when test="companyName !=null and companyName !=''">
company_name like #{companyName}
when>
<when test="bracdName !=null and bracdName !=''">
bracd_name like #{bracdName}
when>
<otherwise>1=1otherwise>
choose>
select>
<delete id="deleteById">
delete frpm mybatis where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
foreach>;
delete>
一个用户有一张订单

<association property="user" javaType="user">
<id column="uid" property="id">id>
<result column="username" property="username">result>
<result column="password" property="password">result>
association>
通过<association>把两张表对应的实体类连接起来,只不过是主键ID要用单独的标签
<select id="findAll" resultMap="orderMap">
SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id
select>
SQL环节和原来没什么区别,同样也是通过resultMap把字段和属性映射封装
一个用户有多张订单

<collection property="orderList" ofType="order">
<id column="oid" property="id">id>
<result column="ordertime" property="ordertime">result>
<result column="total" property="total">result>
collection>
private List orderList;
<select id="findAll" resultMap="userMap">
SELECT *,o.id oid FROM USER u,orders o WHERE u.id=o.uid
select>
多用户多角色

多对多的建表原则是引入一张中间表,用于维护外键,就是一张表通过中间表找到另一张表
和一对多的模型类似,先在User实体类中增添一个“用户具备哪些角色”的属性private ListroleList;其次配置Mapper文件:
<collection property="roleList" ofType="role">
<id column="roleId" property="id">id>
<result column="roleName" property="roleName">result>
<result column="roleDesc" property="roleDesc">result>
collection>
多表的连接是靠中间表,这点在Mapper文件中通过映射实现,具体是把两张外表的id(userId和roleId)在id标签中配置成同一个属性,就像这样:
<id column="userId" property="id">id>
<id column="roleId" property="id">id>
SQL环节就得用多对多的套路了
<select id="findUserAndRoleAll" resultMap="userRoleMap">
SELECT * FROM USER u,user-role ur,role r WHERE u.id=ur.userId AND ur.roleId=r.id
select>
多表操作时MyBatis确实减少了很多硬编码,每一次新的SQL只需要在标签里改几个属性就可以,只要理清字段与属性的映射关系,在MyBatis中进行多表操作就是一个“对号入座”。