mybatis映射文件标签总结

动态sql

Posted by AnAn on August 6, 2018
  • 动态sql:
  • 1.if
      <select id="findUsers1" parameterType="cn.flyingd.domain.User">
          select * from user where 1=1
          <if test="userName !=null ">
              and username = #{userName}
          </if>
    		
          <if test="userSex !=null ">
              and usersex = #{userSex}
          </if>	
      </select>
    
  • 2.where
      <select id="findUsers1" parameterType="cn.flyingd.domain.User">
          select * from user 
          <where>
              <if test="userName !=null ">
                  and username = #{userName}
              </if>
    			
              <if test="userSex !=null ">
                  and usersex = #{userSex}
              </if>
          </where>	
      </select>
    
  • 3.foreach
      <select id="findUsers1" parameterType="cn.flyingd.domain.QueryVo">
          select * from user 
          <where>
              <foreach collection="ids" open="and id in (" close=")" sperator="," item="aaa" >
                  #{aaa}
              </foreach>
          </where>
      </select>
    
  • 4.sql片段
      <sql id="abc" >
          select * from user
      </sql>
    
      <select id="findUsers1" parameterType="cn.flyingd.domain.QueryVo">
           <include refid="abc" />
          <where>
              <foreach collection="ids" open="and id in (" close=")" sperator="," item="aaa" >
                  #{aaa}
              </foreach>
          </where>
      </select>
    
  • 5.Mybatis,多对一,看成了一对一
          public class Account {
      		private User user1;  //持有引用
      	}
    
          public class User {
      	}
    
    • 映射文件IAccountDao.xml ```xml

    ``` select a.*,u.id uid,u.address userAddress,u.sex userSex from account a left join user u on a.uid = u.id

  • 6.一对多
          public class User {
      		private List<Account> accountList;
      	}
    
      	public class Account {
      	}
    
    • 映射文件IUserDao.xml ```xml

    ``` select u.*,a.id aid,a.uid,a.money from user u left join account a on u.id = a.uid

  • 7.Mybatis,多对多,看成一对多
          public class User {
      		private List<Role> roleList;
      	} 
    
          public class Role {
      	}
    
    • IUserDao.xml ```xml
    </resultMap> ``` select u.*,r.id rid,r.role_name from user u left join user_role ur on u.id= ur.uid left join role r on ur.rid = r.id