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
@Update("update user set k1=#{kName} where id=#{id}")
public int updatePwd(@Param("id") Integer id, @Param("kName") String k)throws Exception;
4. Delete
@Select("select * from user where id=#{id}")
public User getUserById(@Param("id") Integer id) throws Exception;