【UserDao.java 】
package com.Higgin.Mybatis.dao; import com.Higgin.Mybatis.po.User; public interface UserDao { //根据id查询用户信息 public User findUserById(int id) throws Exception; //添加用户信息 public void insertUser(User user) throws Exception; //删除用户信息 public void deleteUser(int id) throws Exception; }
【UserDaoImpl.java】
package com.Higgin.Mybatis.dao; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.Higgin.Mybatis.po.User; public class UserDaoImpl implements UserDao{ //需要向Dao实现类中注入SqlSessionFactory private SqlSessionFactory sqlSessionFactory; //这里通过构造方法注入 public UserDaoImpl(SqlSessionFactory sqlSessionFactory){ this.sqlSessionFactory=sqlSessionFactory; } @Override public User findUserById(int id) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); User user=sqlSession.selectOne("test.findUserById",id); //补充一个释放资源的代码 sqlSession.close(); return user; } @Override public void insertUser(User user) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); sqlSession.insert("test.insertUser",user); //提交事务,必须! sqlSession.commit(); //补充一个释放资源的代码 sqlSession.close(); } @Override public void deleteUser(int id) throws Exception { SqlSession sqlSession=sqlSessionFactory.openSession(); sqlSession.delete("test.deleteUser",id); //提交事务 sqlSession.commit(); //补充一个释放资源的代码 sqlSession.close(); } }
【UserDaoTest.java】
【建立Junit测试方法流程】
1.新建一个测试类,右击,选择Junit Test Case
2.如下图选择,点击Next
3.选出需要测试的方法
4.会自动生成以下模板代码
代码如下
package com.Higgin.Mybatis.dao.test; 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 com.Higgin.Mybatis.dao.UserDao; import com.Higgin.Mybatis.dao.UserDaoImpl; import com.Higgin.Mybatis.po.User; public class UserDaoTest{ private SqlSessionFactory sqlSessionFactory; //此方法在执行testFindUserById() 之前执行 @Before public void setUp() throws Exception { //创建sqlSessionfactory //MyBatis配置文件 String resource="SqlMapConfig.xml"; //得到配置文件流 InputStream inputStream=Resources.getResourceAsStream(resource); //创建会话工厂,传入MyBatis的配置文件信息 //这里千万别写成SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); //不然会NullPointerException报错 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testFindUserById() throws Exception { //创建UserDao的对象 UserDao userDao =new UserDaoImpl(sqlSessionFactory); //调用UserDao的方法 User user =userDao.findUserById(4); System.out.println(user.toString()); } }
【运行结果】
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
时间: 2024-10-23 16:01:30