MyBatis--注解式开发

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>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值