1.动态代理
动态代理是使用SqlSession.getMapper(dao接口.class)获取这个借口类的一个对象,也就是创建一个实现类,它是由于mybatis自己完成这个实现类的创建,你只需要在接口类中定义需要操作数据库的方法,例如select.insert等。从我们mybatis的入门项目继续操作。
在入门项目中我们的下面这部分代码基本上是固定的,所以我们将它抽取出来放在一个初始化类中。
//1.定义mybatis主要配置文件的名称,从类路径的根开始(target/clasess)
String config = "mybatis.xml"; //唯一的
//2.读取这个config表示的文件
InputStream fp = Resources.getResourceAsStream(config); //读取到主配置文件的信息
//3.创建SqlSessionFactoryBuilder 对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//4.创建SqlSessionFactory对象
SqlSessionFactory factory = builder.build(fp);
我新建在了com.ajuncode.utils.MyBatisUtils下
代码如下(封装获得SqlSession的类)
package com.ajuncode.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 MyBatisUtils {
private static SqlSessionFactory factory = null;
static {
String config = "mybatis.xml";
try {
InputStream fp = Resources.getResourceAsStream(config);
factory = new SqlSessionFactoryBuilder().build(fp);
}catch (IOException e){
e.printStackTrace();
}
}
//获取SqlSession 方法
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
if (factory!=null){
sqlSession = factory.openSession();
}
return sqlSession;
}
}
在我们的接口类StudentDao中只需要定义操作方法,例如查询和插入。
package com.ajuncode.Dao;
import com.ajuncode.domain.Student;
import java.util.List;
public interface StudentDao {
//这里是查询Student表的方法selectStudents()
//selectStudents 是自定义,与同目录下的StudentDao.xml 操作id的命名保持一致
public List<Student>selectStudents();
//插入方法
//参数:student,表示要插入到数据库的数据
//返回值:int 表示执行insert操作后的影响数据库的行数
public int insertStudent(Student student);
}
2.SqlSession.getMapper(dao接口.class)
我们用一个测试程序来演示效果。在com.ajuncode包下创建一个TstsMybatis1测试文件,注意在pom.xml中添加测试依赖。
package com.ajuncode;
import com.ajuncode.Dao.StudentDao;
import com.ajuncode.domain.Student;
import com.ajuncode.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TestMybatis1 {
@Test
public void testSelectStudents(){
// 使用mybatis 的动态代理机制,使用sqlSesssion.getMapper(dao接口)
// getmapper能够获得dao接口的对应的实现类对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
// 调用dao的方法,执行数据库的操作
List<Student> students = dao.selectStudents();
}
@Test
public void testInsertStudents(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setAge(19);
student.setEmail("xxx@qq.com");
student.setName("xxx");
student.setId(1006);
int num = dao.insertStudent(student);
sqlSession.commit();
}
}
使用动态代理其实是mybatis自动去实现接口类,然后调用这个类的方法直接完成操作,熟悉以后节省很多时间。