Mybatis使用随笔

以前一直用hibernate来的,用了mybatis记点使用中的代码

批量扫描mapper包位置

@MapperScan("com.example.springbootdemo2.dao")

 

一对多有3种方法

第一种:

 1    <resultMap id="userMp" type="com.example.springbootdemo2.entity.UserInfo">
 2         <id column="uid" jdbcType="INTEGER" property="uid"/>
 3         <result column="username" jdbcType="VARCHAR" property="username"/>
4     <!-property 对应类中的list字段,ofType对应list中的类型,下面是查询出来的字段->
5 <collection property="roleList" ofType="com.example.springbootdemo2.entity.SysRole"> 6 <id column="id" jdbcType="INTEGER" property="id"/> 7 <result column="role" jdbcType="VARCHAR" property="role"/> 9 </collection> 10 </resultMap> 11 <select id="selectUserInfoAndRole" parameterType="java.lang.Integer" resultMap="userMp"> 12 SELECT 13 ui.*,sr.* 14 from user_info ui LEFT JOIN sys_user_role sur on(ui.uid = sur.uid) LEFT JOIN sys_role sr on(sur.role_id = sr.id) 15 </select>

第二种

    <resultMap id="roleMp" type="com.example.springbootdemo2.entity.SysRole">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="role" jdbcType="VARCHAR" property="role"/>
        <result column="description" jdbcType="VARCHAR" property="description"/>
        <result column="available" jdbcType="BIT" property="available"/>
     <!-- select中对应一个select查询语句,column对应关联的id-->
<collection property="userInfos" column="id" select="com.example.springbootdemo2.dao.UserInfoMapper.selectUserInfoByRoleId" javaType="List"/> </resultMap> <select id="selectRoleAndUser" parameterType="java.lang.Integer" resultMap="roleMp"> SELECT * from sys_role </select>

 

  <select id="selectUserInfoByRoleId" parameterType="java.lang.Integer" resultMap="userMp">
    SELECT ui.*
    from user_info ui LEFT JOIN sys_user_role sur on(ui.uid = sur.uid)  WHERE sur.role_id = #{role_id,jdbcType=INTEGER}
  </select>

一对一也差不多

  <resultMap id="sfBB" type="com.example.springbootdemo2.entity.SfBookBorrow">
    <id column="sbb_id" jdbcType="INTEGER" property="id" />
    <result column="user_id" jdbcType="INTEGER" property="userId" />
  </resultMap>
  <resultMap id="sfSB" type="com.example.springbootdemo2.dto.SfStudentBook">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <!--property对应类中的变量,resultMap对应查询出来的字段-->
    <association property="sfBookBorrow" resultMap="sfBB" />
  </resultMap>

 

 

 

 

posted @ 2019-11-11 19:30  摩尔迦娜  阅读(107)  评论(0)    收藏  举报