Mybatis增删改查
V哥官网:http://www.vgxit.com
本文对应视频教程:http://www.vgxit.com/course/22
1,概述:
我们上节课学了一下Mybatis的基本入门,这节课我们学习一下Mybatis的增删改查功能。而查询我们之前都讲过了,这里就过在赘述,我们重点讲添加修改删除。
2,封装获取SqlSession的工具类:
package com.vgxit.learn.vgmybatis.ktdm.tool;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* Mybatis工具类
*/
public class MybatisTool {
/**
* SqlSessionFactory单例
*/
private static SqlSessionFactory SQL_SESSION_FACTORY;
/**
* 获取对应的SqlSession
* @return
* @throws IOException
*/
public static SqlSession getSqlSession() throws IOException {
if (SQL_SESSION_FACTORY == null) {
synchronized (MybatisTool.class) {
if (SQL_SESSION_FACTORY == null) {
SqlSessionFactoryBuilder sessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2,加载对应的配置文件
try (Reader configReader = Resources.getResourceAsReader("mybatis-config.xml")) {
//3,创建SqlSessionFactory,SqlSessionFactory在系统中必须是单例的
SQL_SESSION_FACTORY = sessionFactoryBuilder.build(configReader);
}
}
}
}
return SQL_SESSION_FACTORY.openSession();
}
}
3,添加数据
1,在mapper里面定义对应的方法
int addUser(User user);
2,编写对应的映射器->xml文件:
<insert id="addUser" parameterType="com.vgxit.learn.vgmybatis.ktdm.po.User">
insert into user values (null, #{name}, #{gender}, #{age});
</insert>
3,具体调用
private static void add() {
//1,构造用户对象
User user = User.builder()
.name("蔡萝莉")
.gender((short) 2)
.age(21)
.build();
try (SqlSession sqlSession = MybatisTool.getSqlSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int result = userMapper.addUser(user);
System.out.println("添加了" + result + "行数据");
//在mybatis里面默认就是开启了事务的,我们做查询的时候没有影响,但是如果我们做添加,修改删除这种写操作的时候,必须提交事务
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
4,修改数据
1,在mapper里面定义对应的方法
int updateUser(User user);
2,编写对应的映射器->xml文件
<update id="updateUser" parameterType="com.vgxit.learn.vgmybatis.ktdm.po.User">
update user set name=#{name}, gender=#{gender}, age=#{age} where id=#{id}
</update>
3,具体调用
private static void update() {
//获取sqlSession
try (SqlSession sqlSession = MybatisTool.getSqlSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(19);
user.setName("林俊杰");
user.setAge(39);
userMapper.updateUser(user);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
5,删除数据
1,在mapper里面定义对应的方法
int deleteUser(int id);
2,编写对应的映射器->xml文件
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
3,具体调用
private static void delete() {
//获取sqlSession
try (SqlSession sqlSession = MybatisTool.getSqlSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println(userMapper.deleteUser(10));
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
}
}