企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # dao包 创建UserDao接口 ~~~ package dao; import pojo.User; public interface UserDao { // 通过用户ID查询一个用户 public User selectUserById(Integer id); } ~~~ 创建UserDaoImpl类 ~~~ package dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import pojo.User; public class UserDaoImpl implements UserDao { // 注入 private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } // 通过用户ID查询一个用户 @Override public User selectUserById(Integer id) { SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession.selectOne("test.findUserById", id); } // 通过用户名模糊查询 public List<User> selectUserByUsername(Integer id) { SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession.selectList("test.findUserById", id); } } ~~~ # junit 创建MybatisDaoTest类 ~~~ package junit; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; import dao.UserDao; import dao.UserDaoImpl; import pojo.User; public class MybatisDaoTest { public SqlSessionFactory sqlSessionFactory; @Before public void before() throws Exception { // 加载核心配置文件 String resource = "sqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); // 创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } @Test public void testDao() { UserDao userDao = new UserDaoImpl(sqlSessionFactory); User user = userDao.selectUserById(10); System.out.println(user); } } ~~~