-
注解:
- @Insert:添加
- @Update:修改
- @Delete:删除
- @Select:查询
- @Result:实现结果集封装
- @Results:可以和 @Reslult 一起使用,封装多个结果集
- @One:实现一对一和多对一的结果集封装
- @Many:实现一对多结果集封装
-
MyBatis 注解不能实现动态SQL
-
使用:
- SqlMapConfig.xml 配置文件
<mappers><!-- 第一种方式:class引入接口,只能引入一个接口--><mapper class="com.mybatis.Dao.TeacherDao"/><!-- 第二种方法:针对包下边的所用接口--><package name="com.mybatis.Dao"/> </mappers>
- 编写注解:
- 增删改查:
java">@Select("select * from user") <!--结果映射集 字段和数据库的字段一一对应--> @Results(id = "userMap" ,value = {@Result(property = "id",column = "id"),@Result(property = "username",column = "username"),@Result(property = "birthday",column = "birthday"),@Result(property = "sex",column = "sex"),@Result(property = "address",column = "address") }) List<User> findAll();@Select("select * from user where id = #{id}") @ResultMap(value = "userMap") List<User> findById(Integer id);@Select("select * from user where username = #{name}") @ResultMap(value = "userMap") List<User> findByName(String name);@Update("update user set username = #{username},birthday = #{birthday},sex = #{sex},address = #{address} where id = #{id}") int update(User user);@Delete("delete from user where id = #{id}") int delete(Integer id);@Insert("insert into user (username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})") int insert(User user);
- 增删改查:
- 多对一注解查询:
- 立即加载:
java">@Select("select student.*,teacher.Tname from student left join teacher on student.t_id = teacher.id") @Results(id = "StudentMap",value = {@Result(property = "id",column = "id"),@Result(property = "Sname",column = "Sname"),@Result(property = "sex",column = "sex"),@Result(property = "age",column = "age"),@Result(property = "t_id",column = "t_id"),@Result(property = "teacher.Tname",column = "Tname") }) List<Student> SelectStudentTeacher();
- 延迟加载:
java">@Select("select * from student") @Results(id = "StudentMap",value = {@Result(property = "id",column = "id"),@Result(property = "Sname",column = "Sname"),@Result(property = "sex",column = "sex"),@Result(property = "age",column = "age"),@Result(property = "t_id",column = "t_id"),@Result(property = "teacher",column = "t_id",one = @One(select = "com.mybatis.Dao.TeacherDao.findTeacherById")) }) List<Student> SelectStudentTeacher();//teacherDao接口 @Select("select * from teacher where id = #{t_id}") List<Teacher> findTeacherById(Integer t_id);
- 一对多注解查询:
java">@Select("select * from teacher") @Results(id = "teacherMap",value = {@Result(property = "id",column = "id"),@Result(property = "Tname",column = "Tname"),@Result(property = "student",column = "id",many = @Many(select = "com.mybatis.Dao.StudentDao.selectStudentByTeacherId",fetchType = FetchType.LAZY)) //延迟加载 }) List<Teacher> selectTeacherStudent();//studentDao接口 @Select("select * from student where t_id = #{id}") List<Student> selectStudentByTeacherId(Integer id);
- 立即加载:
- SqlMapConfig.xml 配置文件