传统的web开发中会使用dao接口的一个实现类impl来对数据库进行操作。
mybatis的动态代理机制,使用getMapper能自动地获取dao接口的实现类对象
底层的原理是使用了反射
创建一个工具类MyBatisUtils,用于创建唯一的sessionFactory和获取SqlSession:
package org.example.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 { //静态代码块加载的时候,会对sessionFactory进行赋值 private static SqlSessionFactory sessionFactory = null; //静态块在类创建前,进行创建,并只创建一次 static { String config="mybatis.xml"; try { InputStream in = Resources.getResourceAsStream(config); sessionFactory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); } } //获取sqlSession的方法 public static SqlSession getSqlSession(){ SqlSession sqlSession = null; if(sessionFactory != null){ sqlSession = sessionFactory.openSession(true); } return sqlSession; } }
创建的接口StudentDao
package org.example.dao; import org.example.domain.Student; import java.util.List; public interface StudentDao { List<Student> selectStudents(); public int insertStudent(Student student); }
sql映射文件
注意:这里的namespace的值要和相关接口的全限定名称相同,sql语句的id要和接口里面相关方法的名称相同,这样mybaits的动态代理机制才能通过反射的方式寻找到你需要执行sql语句
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.example.dao.StudentDao"> <select id="selectStudents" resultType="org.example.domain.Student"> select id, name, email, age from student order by id </select> <insert id="insertStudent"> insert into student values(#{id}, #{name}, #{email}, #{age}) </insert> </mapper>
使用动态代理进行数据库的查询和插入操作
package org.example; import org.apache.ibatis.session.SqlSession; import org.example.dao.StudentDao; import org.example.domain.Student; import org.example.utils.MyBatisUtils; import org.junit.Test; import java.util.List; public class TestMyBatis { @Test public void testSelects(){ //使用mybatis的动态代理机制,使用getMapper能获取dao接口的实现类对象 //MyBatisUtils是我们自己创建的一个工具类 SqlSession sqlSession = MyBatisUtils.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); List<Student> students = dao.selectStudents(); for (Student stu : students){ System.out.println(stu); } } @Test public void testInsert(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); StudentDao dao = sqlSession.getMapper(StudentDao.class); Student student = new Student(1005, "关羽", "guanyu@qq.com", 30); int num = dao.insertStudent(student); System.out.println(num); } }