关于上一篇的操作我们发现,存在大量的重复代码。为了提高开发的效率。我们将代码进行优化,我们将一些重复的代码提取出来。
和Mybatis的传统dao1~7的步骤一样开发一样,可直接略
原先的代码长这个样子
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class MaybatisTest {
@Test
public void findStudentById() throws Exception {
//1.读取配置文件,生产字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.获取代理对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
//5.执行查询
mapper.deteleId(7);
sqlSession.commit();
}
}
进行代码优化之后
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class MaybatisTest {
private InputStream in;
private SqlSession sqlSession;
private StudentDao studentDao;
@Before//用于在测试方法执行之前执行
public void init() throws Exception {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession();
//4.获取dao的代理对象
studentDao = sqlSession.getMapper(StudentDao.class);
}
@After
//用于在测试方法执行之后执行
public void destroy() throws Exception {
//提交事务
sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
//测试删除操作
@Test
public void testDelete() {
studentDao.deteleId(6);
}
//测试保存操作
@Test
public void saveStudent(){
Student student = new Student();
studnet.setUid(8);
student.setUname("梦想");
student.setPassword(11223F);
student.setBirthday(new Date());
System.out.println(student);
}
}
一样可以运行,是不是代码简便了许多