Mybatis framework----->(3) Comparison of Mybatis object analysis, traditional Dao development and dynamic agent Dao development

One, Mybatis object analysis

1. Several commonly used classes
(1) Resources class
  • Responsible for reading the main configuration file
InputStream in = Resources.getResourceAsStream("mybatis.xml");
(2) SqlSessionFactoryBuilder class
  • Usebuild( ) The method creates a SqlSessionFactory object. Generally, the SqlSessionFactoryBuilder object is created as a local object within the method. The method ends and the object is destroyed.
//3.创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
//4.创建SqlSessionFactory对象
SqlSessionFactory factory = builder.build(in);
(3) SqlSessionFactory interface
  • To create a SqlSession, you need to use the SqlSessionFactory interface openSession() method.
SqlSession sqlSession = factory.openSession();
  • openSession(true): Create a SqlSession with automatic submission function
  • openSession(false): To create a SqlSession with non-automatic submission function, you need to submit it manually
  • openSession():同 openSession(false)
(4) SqlSession interface
  • Defines the methods to manipulate data such as selectOne(), selectList(), insert(), update(), delete(), commit(), rollback()

The SqlSession object is not thread-safe and needs to be used inside the method. Before executing the SQL statement, use openSession() to obtain the SqlSession object. The close() method needs to be called after the SQL statement is executed, so as to ensure that its use is thread-safe.

2. Tools (MyBatisUtil)
public class MyBatisUtil {
    
    

    private static SqlSessionFactory factory = null;
    static {
    
    
        try {
    
    
            String config="mybatis.xml";
            //读取配置文件
            InputStream in = Resources.getResourceAsStream(config);
            //创建SqlSessionFactory对象
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession对象
     */
    public static SqlSession getSqlSession(){
    
    
        SqlSession sqlSession = null;
        if (factory != null){
    
    
            sqlSession = factory.openSession();
        }
        return sqlSession;
    }
}

2. Traditional Dao development and dynamic agent Dao development of MyBatis

1. Traditional Dao development
  • Mainly use the implementation class of Dao interface to operate the database
(1) Create an implementation class of Dao interface
public class StudentDaoImp implements StudentDao
(2) Implement methods in the interface
**
 * 查询
 * @return
 */
@Override
public List<Student> selectStudens() {
    
    
    //获取SqlSession对象
    SqlSession sqlSession = MyBatisUtil.getSqlSession();

    //6.【重要】指定要执行的SQL语句的标识,sql映射文件中的namespace+"."+标签的id值
    String sqlId = "com.hcz.dao.StudentDao"+"."+"selectStudens";
    //7.【重要】执行SQL语句,通过sqlId找到语句
    List<Student> studentList = sqlSession.selectList(sqlId);
    //9.关闭连接
    sqlSession.close();
    return studentList;
}

/**
 * 插入
 * @param student
 * @return
 */
@Override
public int insertStudent(Student student) {
    
    
    //获取SqlSession对象
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    String sqlId="com.hcz.dao.StudentDao"+"."+"insertStudent";
    //执行sql语句, 使用SqlSession类的方法
    int nums = sqlSession.insert(sqlId,student);
    //提交事务
    sqlSession.commit();
    //关闭
    sqlSession.close();
    return nums;
}
(3) Define the test method
@Test
public void testSelectStudents(){
    
    
    StudentDao dao = new StudentDaoImp();
    List<Student> studentList = dao.selectStudens();
    for (Student student:studentList){
    
    
        System.out.println(student);
    }
}

@Test
public void testInsertStudent(){
    
    
    StudentDao dao = new StudentDaoImp();
     Student student = new Student();
     student.setId(1006);
     student.setName("李刚");
     student.setEmail("[email protected]");
     student.setAge(26);
    int result = dao.insertStudent(student);
    System.out.println("添加对象的数据为:"+result);
}

analysis:

StudentDao dao = new StudentDaoImp();
List<Student> studentList = dao.selectStudens();

1. Dao object, the type is StudentDao, the fully qualified name is:com.hcz.dao.StudentDaoIt is the same as the namespace of the mapping file
2. Called by daoselectStudents()The method and the id value in the mapping file are the same.
3. The return value of the method in dao can also determine the method of SqlSession to be called by Mybatis:
(1) If the return value is List, the SqlSession.selectList() method is called
( 2) If the return value is int, or is not a List, if the label in the mapper file is insert, update will call the insert, update and other methods of SqlSession

to sum up:

The Dao class does not actually have any substantive work. It is only used to locate the SQL statement of the corresponding id in the mapping file through the relevant interface method of SqlSession, so the real operation of the database is actually done by the framework through the Sql statement in the mapping file. .

2. Dynamic agent Dao development
  • Dynamic proxy mode (jdk dynamic proxy mechanism):

The MyBatis framework sets aside Dao's implementation class, creates a dao interface implementation class based on your dao interface, and creates an object of this class, completes calling the methods in the dao interface, and then directly locates the corresponding in the mapping file SQL statement for database operations

(1) Obtain the implementation class corresponding to the dao interface through SqlSesssion.getMapper (dao interface)
StudentDao dao = MyBatisUtil.getSqlSession().getMapper(StudentDao.class); 
(2) Call the corresponding method in the interface to execute the SQL statement in the mapping file through the obtained dao interface implementation class
List<Student> studentList = dao.selectStudens();

Guess you like

Origin blog.csdn.net/hcz666/article/details/113061978