MyBatis注解详解:@Select、@Insert、@Update、@Delete实现CRUD操作
MyBatis注解实现数据库增删改查操作
本文将介绍如何使用MyBatis注解简化数据库操作,通过@Select、@Insert、@Update和@Delete注解配合SQL语句,实现对数据库表t_comment的增删改查操作。
代码示例
@Mapper
public interface CommentMapper {
@Select('SELECT * FROM t_comment WHERE id = #{id}')
Comment getCommentById(Long id);
@Insert('INSERT INTO t_comment (content, user_id, create_time) VALUES (#{content}, #{userId}, #{createTime})')
void insertComment(Comment comment);
@Update('UPDATE t_comment SET content = #{content}, user_id = #{userId}, create_time = #{createTime} WHERE id = #{id}')
void updateComment(Comment comment);
@Delete('DELETE FROM t_comment WHERE id = #{id}')
void deleteComment(Long id);
}
代码解读
- @Mapper注解: 标识该接口为MyBatis的Mapper接口,会被MyBatis扫描到并生成代理对象。
- @Select、@Insert、@Update、@Delete注解: 分别对应SQL语句中的查询、插入、更新和删除操作。注解的值为对应的SQL语句字符串。
- 占位符: 在SQL语句中使用
#{parameterName}来引用方法参数,MyBatis会自动将参数值填充到占位符的位置。
注意
- 示例代码中的
Comment类需要与数据库表t_comment的结构对应,并包含相应的属性和对应的getter/setter方法。 - 在其他地方使用该接口时,只需注入接口并调用对应的方法即可完成相应的数据库操作。
总结
使用MyBatis注解可以简化数据库操作代码,提高代码的可读性和可维护性。通过在接口方法上使用注解,我们可以在接口内部直接完成对数据库表的增删改查操作。
原文地址: https://www.cveoy.top/t/topic/HfU 著作权归作者所有。请勿转载和采集!