1、添加
@Insert("insert into student (sid,sname,sage,ssex) values (#{sid},#{sname},#{sage},#{ssex})")
int addStudent(Student student);
@Test
public void addStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
int res = 0;
//res返回值大于0,一般返回1,表示sql执行成功,为0,表示sql执行失败
try {
res = studentDao.addStudent(new Student(9,"kang",sdf.parse("1994-05-08"),"男"));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(res);
//提交事务
sqlSession.commit();
sqlSession.close();
}
2、删除
@Delete("delete from student where sid=#{id}")
int deleteStudent(@Param("id") int id);
@Test
public void deleteStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int res = studentDao.deleteStudent(9);
System.out.println(res);
sqlSession.commit();
sqlSession.close();
}
3、修改
@Update("update student set sname=#{newsname} where sname=#{oldsname}")
int updateStudent(@Param("oldsname") String oldName,@Param("newsname") String newName);
public void updateSudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
int res = studentDao.updateStudent("kang","kang111");
System.out.println(res);
sqlSession.commit();
sqlSession.close();
}
-
所有的增删改操作都需要提交事务!
-
接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
-
有时候根据业务的需求,可以考虑使用map传递参数!
-
为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!