Mybatis framework -----> (2) Detailed mapping file and configuration file

One, create a mapping file

Claim
  1. Create a file StudentDao.xml in the dao package
    Insert picture description here
  2. The StudentDao.xml file name is required to be the same as the interface StudentDao, case sensitive
<?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="com.StudentDao">
    <select id="selectStudens" resultType="Student">
      select * from student order by id
    </select>
    <!--插入操作-->
    <insert id="insertStudent">
        insert into student values (#{id},#{name},#{email},#{age})
    </insert>
</mapper>
        
  1. Parse the parameters inside:
  • namespace value:

It is recommended to use the fully qualified name of the dao interface, here is com.hcz.dao.StudentDao

  • select tag:

Represents query operations; in addition, the
update label represents the operation of updating the database; the
insert label represents the insert operation; the
delete label represents the delete operation

  • id value:

Indicates the unique identifier of the SQL statement to be executed. Mybatis will use the value of this id to find the SQL statement to be executed. It can be customized, but you are required to use the method name in the dao interface. The interface method name queried here isselectStudens

  • resultType value:

Indicates the result type, which is the ResultSet obtained after the SQL statement is executed, and the Java object type is obtained by traversing the ResultSet. Its value must use the fully qualified name, here iscom.hcz.dao.Student

  1. Approximate the code in jdbc
<select id="selectStudens" resultType="Student"> 
      select id,name from student 
</select>

Approximately equivalent to the following jdbc code

//执行查询,创建记录集
        rs = st.executeQuery("select * from text ");
        while (rs.next()){
    
    
            Student stu = new Student();
            stu.setId(rs.getInt("id"));
            stu.setName(rs.getString("name"));
            //从数据库取出的数据转为Student对象,封装到List集合中
            stuList.add(stu);
        }

Two, create a configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

    <!--配置mybatis环境:数据库的连接信息-->
    <environments default="mysql">
        <!--id:数据源的名称-->
        <environment id="mysql">
            <!--配置事务类型:使用jdbc事务(使用Connection的提交和回滚)-->
            <transactionManager type="JDBC"/>
            <!--数据源dataSource:创建数据库Connection对象的commit,rollback做事务处理
                type:POOLED使用数据库的连接池
            -->
            <dataSource type="POOLED">
                <!--连接池四要数-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3366/ssm?useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="com/hcz/dao/StudentDao.xml"/>
    </mappers>
</configuration>
  • settings tag

The mybatis.xml file is added to the log configuration, and the executed sql statements and parameters can be output in the console

  • mappers tag: the location of the sql mapping file

Tell mybatis the location of the SQL statement to be executed
from the root of the classpath:target/classesClasspath

Three, create a test class

public class MyTest {
    
    

    public static void main(String[] args) {
    
    
        //访问mybatis读取student数据
        try {
    
    
            //1.定义mybatis主配置文件,从类路径的根开始(target/classes)
            String config = "mybatis.xml";
            //2.读取配置文件,Resources: mybatis中的一个类, 负责读取主配置文件
            InputStream in = Resources.getResourceAsStream(config );
            //3.创建SqlSessionFactoryBuilder对象 : 创建SqlSessionFactory对象
            SqlSessionFactoryBuilder builder  = new SqlSessionFactoryBuilder();
            //4.创建SqlSessionFactory对象
            SqlSessionFactory factory = builder.build(in);
            //5.获取SqlSession对象,从SqlSessionFactory中获取SqlSession
            /**
             * 1. openSession() :无参数的, 获取是非自动提交事务的SqlSession对象
             * 2. openSession(boolean): openSession(true)  获取自动提交事务的SqlSession.
             *       openSession(false)  非自动提交事务的SqlSession对象
             *
             */
            SqlSession sqlSession = factory.openSession();
            /**
             * SqlSession接口 :定义了操作数据的方法 例如 selectOne() ,selectList() ,
             *                  insert(),update(), delete(), commit(), rollback()
             */
            //6.【重要】指定要执行的SQL语句的标识,sql映射文件中的namespace+"."+标签的id值
            String sqlId = "com.hcz.dao.StudentDao"+"."+"selectStudens";
            //7.【重要】执行SQL语句,通过sqlId找到语句
            List<Student> studentList = sqlSession.selectList(sqlId);
            //8.输出结果
            //studentList.forEach(student -> System.out.println(student));
            for (Student student:studentList){
    
    
                System.out.println(student);
            }
            //9.关闭连接
            sqlSession.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}
  • Equivalent code
//6.【重要】指定要执行的SQL语句的标识,sql映射文件中的namespace+"."+标签的id值
String sqlId = "com.hcz.dao.StudentDao"+"."+"selectStudens";
//7.【重要】执行SQL语句,通过sqlId找到语句
List<Student> studentList = sqlSession.selectList(sqlId);

Approximately equivalent to jdbc code

Connection conn = 获取连接对象 
String sql=” select id,name,email,age from student” 
PreparedStatement ps = conn.prepareStatement(sql); 
ResultSet rs = ps.executeQuery();

Guess you like

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