您好,欢迎来到花图问答。
搜索
您的当前位置:首页MyBatis--注解式开发

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>

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务