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(); }
-- 现在只是测试,后期会优化
update t_user set username='root',password='root' where id=2;
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 from t_user where id=3;
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 * from t_user;
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(); } }