The basis of Mybatis

1. Description of mapper file of Mybatis

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

mybatis-3-mapper.dtdConstraint file for Mybatis

2. Java code executes Sql (the initial state of the Mybatis framework [to simplify])

        //访问mybatis去读取数据
        //1.定义mybatis的主配置文件的名称,从类路径的根开始(target/classes)
        String config ="xxxx.xml";
        //2.读取这个xml
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4.创建SqlSessionFactory对象
        SqlSessionFactory factory = builder.build(in);
        //5.从factory中获取sqlSession
        SqlSession sqlSession = factory.openSession();
        //6、sql语句的执行  命名空间+"."+"标签的id值"
        String sql="com.lgz.dao.StudentDao"+"."+"selectStudentList";
        //7.sql执行
        List<Object> objects = sqlSession.selectList(sql);
        //8.关闭SqlSession对象
        sqlSession.close();
  1. SqlSession:
    sqlSession interface: defines methods to manipulate data, such as selectOne(), insert(), commit(), etc. sqlSession implementation class DefaultSqlSession
    use requirements: SqlSession object is not thread-safe and needs to be used inside the method. Before executing the sql statement, use openSession to get the SqlSession, after the execution, you need to close it and execute SqlSession.close. This can ensure the use of thread safety.

1. The dynamic proxy mechanism of Mybatis.

Student dao = sqlSession.geMapper(StudentDao.class);
//sqlSession.getMapper可以获取dao接口对应的实现类对象

2. Passing parameters of Mybatis Pass
the data from the java code to the sql statement of the mapper file.
1), parameterType: an attribute written in the mapper file. Represents the data type of the parameter of the method in the dao interface, the reflection mechanism of mybatis can also read the parameter parameter, so it is not necessary to write
public Student selectoneById(Integer id)

3. Parameters

1. A simple type parameter: #{}
2. Multiple simple type parameters, use @Param("custom name")
3. Use a Java object, the attribute value of the object is used as the mapper file to find the parameter, #{ Java The attribute name of the object}
4. The position of the used parameter, syntax #{arg0}, #arg{1}

4. Label

<include refid="T_rh_order.columns"/>
<sql id="T_rh_order.columns">
    xxx 
 <sql/>

Guess you like

Origin blog.csdn.net/qq_40738693/article/details/114522154