Mybatis知识点总结
参考资料
实用的动态sql写法记录
基础的增删查改
总结:使用自增主键,会返回自增的主键值封装到之前没有id值的对象中。调用增加方法之后,之前的对象就有了id(主键)值
@Insert("insert into student(name,age) values(#{name},#{age})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
boolean addStudent(Student student);
@Update("<script>" +
"update student" +
"<set>" +
"<if test='age!=null'>age=#{age}</if>," +
"<if test='name!=null'>name=#{name}</if>" +
"</set>" +
"where id=#{id}" +
"</script>")
boolean updateStudent(Student student);
//模糊查询
@Select("select * from student where name like concat('%',#{likeName},'%')")
List<Student> findByLike(String likeName);
@Delete("delete from student where id =#{id}")
boolean deleteStudent(Integer id);
增删改的批量处理
批量增加数据
使用动态sql语句--foreach
//批量增加
@Insert("<script>" +
"insert into student(age,name) values" +
"<foreach item='s' collection='students' separator=',' >" +
"(" +
"#{s.age},#{s.name}" +
")" +
"</foreach>" +
"</script>"
)
void addBatch(@Param("students") List<Student> students);
批量更新
方式1:foreach循环组装sql
使用该方式的前提:Mybatis映射文件中的sql语句默认是不支持以" ; " 结尾的,也就是不支持多条sql语句的执行。所以需要在连接mysql的url上加 &allowMultiQueries=true 这个才可以执行。
//批量更新
//方式1:foreach,循环拼接sql语句。";"隔开每条单独的sql语句
// separator=";" 代表着每次循环完,在sql后面放一个分号
@Update("<script>" +
"<foreach collection='students' item='s' separator=';'>" +
"update student set name=#{s.name} where id=#{s.id}" +
"</foreach>" +
"" +
"</script>")
void updateBatch(@Param("students") List<Student> students);
优缺点:需要修改mysql的连接url,让全局支持多sql执行,不太安全
方式2:case when的sql语句
优缺点:
优点:不需要添加url参数;
缺点:每一个case when 都要循环一遍list集合,所以大批量拼sql的时候会比较慢。生成多条拼接sql,sql长度过长,容易sql超长引起报错 Packet for query is too large。
对应的Sql:
#使用SQL一次批量更新多条记录
UPDATE stu
SET
student_name = (
CASE
WHEN teacher_id=2 then '2号老师的学生'
END
),
student_age = (
CASE
WHEN teacher_id = 2 then 22
END
)
WHERE teacher_id IN (2,3)
//批量更新---case when 语句
@Update("<script>" +
"update student set name=(case" +
"<foreach collection='students' item='s' >" +
"<if test='s.name!=null'>when id=#{s.id} then #{s.name}</if>" +
"</foreach>end)" +
" where id in " +
"<foreach collection='students' item='s' open='(' separator=',' close=')'>" +
"#{s.id}" +
"</foreach>" +
"</script>")
void updateBatch2(@Param("students") List<Student> students);
测试前数据库
//批量更新---case when 语句
@org.junit.Test
public void testUpdateBatch(){
Student student = new Student(3,18, "胡歌55");
Student student1 = new Student(4,26, "霍建华55");
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student);
studentDao.updateBatch2(students);
}
测试后数据库
后台sql语句显示
批量删除
多条件的批量删除
/**
* 批量删除
* @param list
* @return
*/
@Delete("<script>" +
"delete from lpsa_notationcontent where " +
"<foreach collection='list' item='i' separator='or'>" +
"type=#{i.type} and typeId=#{i.typeId} and project_id=#{i.projectId}" +
"</foreach>" +
"</script>")
Boolean batchDeleteNotationContent(List<NotationContent> list);
多表的操作
多表删除