🍓个人主页:个人主页
🍒系列专栏:SSM框架
💬推荐一款模拟面试、刷题神器,从基础到大厂面试题👉点击跳转刷题网站进行注册学习
目录
1.创建sqlSession工具类
2.测试修改功能
3.测试删除功能
4.测试查询功能
1.创建sqlSession工具类
在MyBatis 使用中,如果每个方法执行时都需要读取配置文件,并根据配置文件的信息构建SqlSessionFactory对象,然后创建SqlSession 对象,这会导致类大量的重复代码。为了简化开发,需要将重复代码封装到一个工具类中。如下:
package com.atguigu.mybatis.utils;
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.InputStream;
public class SqlSessionUtils {
public SqlSession getSqlSession() {
SqlSession sqlSession = null;
{
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
}
return sqlSession;
}
}
后面的 修改 删除 查询 只是简单测试,后期会优化。
2.测试修改功能
public interface UserMapper {
/** 修改用户信息 */
void updateUser();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.mapper.UserMapper">
<update id="updateUser">
-- 现在只是测试,后期会优化
update t_user set username='root',password='root' where id=2;
</update>
</mapper>
public class MybatisTest {
@Test
public void test() {
SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
SqlSession sqlSession = sqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.updateUser();
sqlSession.close();
}
}
运行后:
3.测试删除功能
public interface UserMapper {
/** 删除用户信息 */
void deleteUser();
}
<delete id="deleteUser"> delete from t_user where id=3; </delete>
public class MybatisTest {
@Test
public void test() {
SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
SqlSession sqlSession = sqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteUser();
sqlSession.close();
}
}
4.测试查询功能
public interface UserMapper {
/** 查询用户信息 */
List<User> getAllUser();
}
注意:查询的标签
select
必须设置属性
resultType
或
resultMap
,用于设置实体类和数据库表的映射关系resultType
:自动映射,用于属性名和表中字段名一致的情况resultMap
:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况
<select id="getAllUser" resultType="com.atguigu.mybatis.pojo.User">
select * from t_user;
</select>
public class MybatisTest {
@Test
public void test() {
SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();
SqlSession sqlSession = sqlSessionUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> allUser = userMapper.getAllUser();
allUser.forEach(System.out::println);
sqlSession.close();
}
}