mybatis增删改
- 概念:
- 功能:从应用程序角度出发,软件具有哪些功能;
- 业务:完成功能时的逻辑,对应service的一个方法;
- 事务:从数据库角度出发,完成业务时需要执行的SQL集合,统称一个事务。
- mybatis 底层是对 JDBC 的封装
- JDBC 中 executeUpdate()执行新增,删除,修改的 SQL.返回值 int,表示受影响的行数。
- 所以mybatis 中<insert><delete><update>标签没有 resultType 属性,默认返回值都是 int。
- 增加一条信息
- 使用<insert>标签
<insert id="ins" parameterType="People">
insert into people values(default,#{name},#{age})
</insert>People people = new People();
people.setName("新增name");
people.setAge(88);
try {
int insert = session.insert("com.bjm.mapper.ins", people);
if (insert>0) {
System.out.println("成功");
}else {
System.out.println("失败");
}
} catch (Exception e) {
session.rollback();
}
session.commit();
session.close(); - 在 openSession()时 Mybatis 会创建 SqlSession 时同时创建一个Transaction(事务对象),同时 autoCommit 都为 false,这也就是mybatis将JDBC的自动提交关闭,需要session.commit();让session进行提交。
- 为了避免错误提交,使用session.rollback();事务回滚
- 使用<insert>标签
- 删除一条信息
- 使用<delete>标签
<delete id="del" parameterType="People">
delete from people where id=#{0}
</delete>try {
int delete = session.delete("com.bjm.mapper.del", 2);
if (delete > 0) {
System.out.println("成功");
}else {
System.out.println("失败");
}
} catch (Exception e) {
session.rollback();
} - 由于删除操作是根据id查找一条数据,所以使用#{0}
- 使用<delete>标签
- 修改一条信息
- 使用<update>标签
<update id="upd" parameterType="People">
update people set name = #{name} where id = #{id}
</update>People people = new People();
people.setId(3);
people.setName("王二麻子");
try {
int update = session.update("com.bjm.mapper.upd", people);
if (update > 0) {
System.out.println("成功");
}else {
System.out.println("失败");
}
} catch (Exception e) {
session.rollback();
}
session.commit();
session.close();
- 使用<update>标签