6、java mybatis 添加、修改、删除

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都写上!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值