Mybatis 实现CRUD

Mybatis 实现CRUD(新手)


1.Create

  • v1 2 3 4 为 Role 实体类中属性值一一对应 k1 2 3 4
@Insert("insert into role(k1,k2,k3,k4) values(#{v1},#{v2},#{v3},#{v4})")
public int add(Role role) throws Exception;

2.Retrieve

  • 简单查询,注意属性值与表中字段相同一一对应
@Select("select * from user where id=#{id}")
public User getUserById(@Param("id") Integer id) throws Exception;
  • 不确定条件,可以有 userName也可以有userRolename,也可以都没有
  • #{} 内取值为传入参数 map 中的 key 多对应的 value 
<select id="countUser" parameterMap="map" resultType="Pojo">
    select * from user
    <where>
        <if test="userName != null">
            userName=#{userName}
        </if>
        <if test="userRole != null">
            and userRoleName=#{userRole}
        </if>
    </where>
</select>
  • 模糊查询 
  • 使用 concat('%','${pattern}','%') 来实现模糊查询
  • Java 字符串占位符采用 $ 使用 '#{pp}' 会引发异常
@Select("select * from books where bookName like concat('%', '${namePattern}', '%')")
List<Books> queryBooksByNameLikely(@Param("namePattern") String bookNamePattern);
  • 多对一问题(关联):Student 实体类中有 Teacher 属性
  • 使用标签 association 嵌套查询,并且标签 association 的属性值 javaType 代表 查询当前实体类中所绑定的实体类的类型
  • property 代表实体类中的属性名,column 代表查询结果表的字段别名
<select id="getStudent" resultMap="StudentTeacher">
    select s.id sid, s.name sname, t.name tname, s.tid tid
    from student s, teacher t
    where s.tid=t.id;
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
    </association>
</resultMap>
  • 一对多问题(集合):Teacher 实体类中有 Student 属性
  • 使用标签 collection 嵌套查询,并且标签 collection 中属性值 ofType 代表集合中泛型的实体类的类型
  • property 代表实体类中的属性名,column 代表查询结果表的字段别名
<select id="getTeacherInfo" resultMap="TeacherStudent">
    select t.id tid, t.name tname, s.name sname, s.id sid
    from teacher t, student s
    where t.id=s.tid and t.id=#{tid}
</select>

<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="Student">
        <result property="name" column="sname"/>
        <result property="id" column="sid"/>
    </collection>
</resultMap>

3. Update

  • #{} 内取值要与接口方法中@Param中值相同
@Update("update user set k1=#{kName} where id=#{id}")
public int updatePwd(@Param("id") Integer id, @Param("kName") String k)throws Exception;

4. Delete

  • #{} 内取值要与接口方法中@Param中值相同
@Select("select * from user where id=#{id}")
public User getUserById(@Param("id") Integer id) throws Exception;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值