测试修改和删除用户的功能
创建SqlSessionUtil工具类
public class SqlSessionUtil {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
//获取核心文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取sql的会话对象SqlSession(会自动提交事务),是MyBatis提供的操作数据库的对象
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
UserMapper 接口
public interface UserMapper {
/**
* 修改用户信息
*/
void updateUser();
/**
* 删除用户信息
*/
void deleteUser();
}
MyBatis的核心配置文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.UserMapper">
<!--
mapper接口和映射文件要保证两个一致:
1.mapper接口的全类名和映射文件的namespace一致
2.mapper接口中的方法的方法名要和映射文件中的sql的id保持一致
-->
<!--void updateUser();-->
<update id="updateUser">
update t_user set username='root',password='123' where id = 3
</update>
<!--void deleteUser();-->
<delete id="deleteUser">
delete from t_user where id = 4
</delete>
</mapper>
测试
public class MyBatisTest {
@Test
public void testInsert() throws IOException {
//获取核心配置文件的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取sql的会话对象SqlSession(不会自动提交事务),是MyBatis提供的操作数据库的对象
//SqlSession sqlSession = sqlSessionFactory.openSession();
//获取sql的会话对象SqlSession(会自动提交事务),是MyBatis提供的操作数据库的对象
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//获取UserMapper的代理实现类对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用mapper接口中的方法,实现添加用户信息的功能
int result = mapper.insertUser();
//通过sql语句的唯一标识找到sql并执行,唯一标识是namespace.sqlId
//int result = sqlSession.insert("com.atguigu.mybatis.mapper.UserMapper.insertUser");
System.out.println("结果:"+result);
//提交事务
//sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
@Test
public void testUpdate(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser();
sqlSession.close();
}
@Test
public void testDelete(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser();
sqlSession.close();
}
}