1.Mybatis常用注解
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
2.基于注解的增删改查
@Insert("insert into student_tb(name,sex,age,height,s_address) values(#{name},#{sex},#{age},#{height},#{sAddress})")
@SelectKey(keyProperty = "id",keyColumn = "id",before = false,statement = "select last_insert_id()",resultType = Integer.class)
int addStudent(Student student);
@Delete("delete from student_tb where id = #{id}")
int deleteStudent(int id);
@Update("update student_tb set name = #{name},age=#{age},sex=#{sex},height=#{height}, s_address = #{sAddress} where id = #{id}")
int updateStudent(Student student);
@Select("select * from student_tb where id = #{id}")
//@ResultType(Student.class) 可以省略 设置返回值类型
Student findStudentById(int id);
@Select("select * from student_tb where id = #{id}")
@Results(id = "studentMap",value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "name",column = "name"),
@Result(property = "sex",column = "sex"),
@Result(property = "height",column = "height"),
@Result(property = "sAddress", column = "s_address")
}) //Resuts 相当于<resultMap @Result相当于<result
Student findStudentById2(int id);
@Select("select * from student_tb")
//@ResultType(Student.class) 可以省略
@ResultMap("studentMap")
List<Student> findAllStudent();
/*
* 当mybatis 方法参数为多个时,可以使用以下几个方式传参
* 1.传对象 传map
* 2.使用arg0 arg1...... 或者 param1 param2等命名
* 3.先将参数声明,再使用@Param给参数命名
*
* */
/*org.apache.ibatis.binding.BindingException:
Parameter 'name' not found. Available parameters are [arg1, arg0, param1, param2]*/
//@Select("select * from student_tb where name like #{arg0} and sex=#{arg1}")
//@Select("select * from student_tb where name like #{param1} and sex=#{param2}")
@Select("select * from student_tb where name like #{name} and sex=#{sex}")
List<Student> findAllStudentByNameAndSex(@Param("name") String nameaa,@Param("sex") String sexxx);
3.一对多查询
@Select("select * from student_tb")
@Results(id = "studentMap2",value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "sex",column = "sex"),
@Result(property = "age",column = "age"),
@Result(property = "name",column = "name"),
@Result(property = "height",column = "height"),
@Result(property = "sAddress",column = "s_address"),
@Result(property = "scoreList",column = "id",many = @Many(
select = "com.qfedu.dao.IScoreDao2.findScoreById",fetchType = FetchType.EAGER
))
})
List<Student>findAllStudentWithScoreList();
4.注解式开启缓存
dao接口上之间加入此注解
// 开启缓存
@CacheNamespace(blocking = true)
5. 当mybatis 方法参数为多个时(报错,解决)
当mybatis 方法参数为多个时,可以使用以下几个方式传参
1.传对象 传map,将数据封装成对象、map等传递
2.使用arg0 arg1...... 或者 param1 param2等命名(注意从0或1开始)
3.先将参数声明,再使用@Param给参数命名