mybatis注解的详解和开发(增、删、改、查以及一对一、一对多/多对一、多对多

注解的基本理解和开发(增、删、改、查以及一对一、一对多/多对一、多对多的关系联查) 使用注解开发的原因?
注解提供了一种简单的方式来实现简单映射语句,而不会引入大量的开销 。能够读懂别人写的代码,特别是框架相关的代码 。本来可能需要很多配置文件,需要很多逻辑才能实现的内容,就可以使用一个或者多个注解的方式来代替,这样就使得编程更加的简洁,代码更加清晰 。
由于开发越来越流行,也可以使用注解开发方式,这样我们可以减少编程时编写的映射文件 。此次是围绕着一些基本的CRUD来学习,再学习复杂的映射关系和延迟加载 。
基本常用的注解有:
@: 实现新增
@:实现更新
@:实现查询
@:实现结果集封装
@:可以与@一起使用,封装多个结果的集合(其内使用@处理当前对象的基本属性,再处理返回值)
@:实现引用@定义的封装
@One:实现一对一结果集 封装
@Many:实现一对多结果集封装
@:实现动态SQL映射
@:实现注解二级缓存的使用
注意:复杂的注解不好编写的情况下可以使用文件配合使用
1、基本的增、删、改、查(单表操作)
在接口中使用注解的方式操作数据库数据
package com.etime.mapper;import com.etime.pojo.Student;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import java.util.List;public interface StudentMapper {//使用@Select注解查询所有学生信息@Select("select * from student")List getAllStudent();//使用@Insert注解向学生表中插入数据@Insert("insert student(sname,cid) values(#{sname},#{cid})")int addStudent(Student student);//使用@Delete注解根据学生id删除学生信息@Delete("delete from student where sid=#{sid}")int delStudent(int sid);//使用@Update注解根据学生id更新学生数据库信息@Update("update student set sname=#{sname} where sid=#{sid}")int updateStudent(Student student);}
测试:
//通过@Select注解方式查询学生的所有信息@Testpublic void t04(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);List studentList = studentMapper.getAllStudent();studentList.forEach(System.out::println);}//通过@Insert注解向学生表中插入数据@Testpublic void t05(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);int row = studentMapper.addStudent(new Student(0,"王小二",2));System.out.println("数据库影响行数:"+row);}//通过@Delete注解根据学生id删除学生信息@Testpublic void t06(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);int row = studentMapper.delStudent(7);System.out.println("数据库受影响行数:"+row);}//通过@Update注解根据学生id更改学生信息@Testpublic void t07(){SqlSession sqlSession = sqlSessionUtil.getSqlSession();StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);//注意这里的学生对象不能够使用匿名对象,因为需要设置学生更新条件idStudent student = new Student(3,"缓缓",2);int row = studentMapper.updateStudent(student);System.out.println("数据库影响行数:"+row);}
运行结果:
2、复杂关系的注解(一对一、一对多/多对一、多对多关系) 相关注解介绍 : @注解:
@代替了标签< > 该注解中可以使用单个@注解,也可以使用@集合
格式:
@ ({@ () , @ ()}) 或者@ (@())
@ 注解: