MyBatis--注解式开发

来源:互联网 发布:复合vb 编辑:程序博客网 时间:2024/06/06 00:34

MyBatis–注解式开发

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

1.@Insert

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

2.@SelectKey

用于替换xml中的标签,用于返回新插入数据的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的位置了。需要使用标签

<!-- 注册映射文件 --><mappers>      <package name="com.hcx.dao"/>  </mappers>
原创粉丝点击