删除:
1、编写接口方法注解
//根据id删除用
@Delete("delete from user where id = #{id}")
int deleteUser(@Param("id")int id);
2、测试
@Test
public void testDeleteUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
mapper.deleteUser(6);
session.close();
}
【注意点:增删改一定记得对事务的处理】
关于@Param
@Param注解用于给方法参数起一个名字。以下是总结的使用原则:
-
在方法只接受一个参数的情况下,可以不使用@Param。
-
在方法接受多个参数的情况下,建议一定要使用@Param注解给参数命名。
-
如果参数是 JavaBean , 则不能使用@Param。
-
不使用@Param注解时,参数只能有一个,并且是Javabean。
#与$的区别
-
#{} 的作用主要是替换预编译语句(PrepareStatement)中的占位符? 【推荐使用】
INSERT INTO user (name) VALUES (#{name});
INSERT INTO user (name) VALUES (?); -
${} 的作用是直接进行字符串替换
INSERT INTO user (name) VALUES ('${name}');
INSERT INTO user (name) VALUES ('kuangshen');
使用注解和配置文件协同开发,才是MyBatis的最佳实践!