MyBatis--注解式开发

MyBatis--注解式开发

MyBatis的注解,主要是用于替换映射文件。而映射文件中无非存放着增删改查的sql映射标签。所以,MyBatis注解,就是替换映射文件中的sql标签。

1.@Insert

其value属性用于指定要执行的insert语句。

2.@SelectKey

用于替换xml中的<selectKey/>标签,用于返回新插入数据的id值。

@SelectKey(statement="select @@identity",resultType=int.class,keyProperty="id",before=false
  • statement:获取新插入记录主键值得sql语句
  • keyProperty:获取的该主键值返回后初始化对象的那个属性
  • resultType:返回值类型
  • before:指定主键的生成相对于insert语句的执行先后顺序,该属性不能省略

3.@Delete

其value属性用于指定要执行的delete语句。

4.@Update

其value属性用于指定要执行的update语句。

5.Select

其value属性用于指定要执行的select语句。

程序举例:

1.修改dao接口:

public interface IStudentDao {
    @Insert(value={"insert into student(name,age,score) values(#{name},#{age},#{score})"})
    void insertStudent(Student student);    
    
    @Insert("insert into student(name,age,score) values(#{name},#{age},#{score})")
    @SelectKey(statement="select @@identity",resultType=int.class,keyProperty="id",before=false)
    void insertStudentCacheId(Student student);
    
    @Delete(value="delete from student where id=#{id}")
    void deleteStudentById(int id);
    
    @Update("update student set name=#{name},age=#{age},score=#{score} where id=#{id}")
    void updateStudent(Student student);
    
    @Select("select * from student")
    List<Student> selectAllStudents();
    
    @Select("select * from student where id=#{id}")
    Student selectStudentById(int id);
    
    @Select("select * from student where name like '%' #{name} '%'")
    List<Student> selectStudentsByName(String name);
    
}

2.删除映射文件

3.修改主配置文件

由于没有了映射文件,所以主配置文件中不能使用<mapper/>注册mapper的位置了。需要使用<package/>标签

<!-- 注册映射文件 -->
<mappers>  
    <package name="com.hcx.dao"/>  
</mappers>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,700评论 0 4
  • Java数据持久化之mybatis 一. mybatis简介 1.1 原始的JDBC操作: Java 通过 Jav...
    小Q逛逛阅读 4,977评论 0 16
  • 1 引言# 本文主要讲解JDBC怎么演变到Mybatis的渐变过程,重点讲解了为什么要将JDBC封装成Mybait...
    七寸知架构阅读 76,641评论 36 979
  • Spring 技术笔记Day 1 预热知识一、 基本术语Blob类型,二进制对象Object Graph:对象图...
    OchardBird阅读 1,005评论 0 2
  • 下公交车的时候雨好大,我把裤脚挽了起啦,裤子基本没怎么湿。但是鞋子的确是湿了,肩膀也湿了一小片。现在坐在办公室里,...
    OCTA阅读 255评论 0 0