Mybatis framework – Study Notes Day01

1. Mybatis overview

Mybatis is a persistence layer framework written in Java.

It encapsulates many details of JDBC operations, so that developers only need to pay attention to the SQL statement itself, and do not need to pay attention to the registration of drivers, creating connections and other complex processes. It uses ORM to achieve the encapsulation of result sets.

ORM: Object Relational Mappging Object Relational mapping

Simply said: is the database table and entity class and entity class attributes corresponding, so that we can operate entity class to achieve operation database table.

2. Introduction to mybatis

2.1 Environment construction of Mybatis

Step 1: Create the Maven project and import the coordinate POM.xml

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day01_eesy_01mybatis</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <packaging>jar</packaging>      <! -- Set packing mode here -->

    <dependencies>
        <dependency>   <! -- Import mybatis coordinates, this is a dependency dependency -->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>    <! -- database -->
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <dependency>        <! - log - >
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>

        <dependency>    <! Unit test -->
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>

</project>
Copy the code

Step 2: Create interfaces for the entity class and DAO user.java and iUserDao.java

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;


public class User implements Serializable {

    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId(a) {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday(a) {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex(a) {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress(a) {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\' ' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\' ' +
                ", address='" + address + '\' ' +
                '} '; }}Copy the code
package com.itheima.dao;

import com.itheima.domain.User;

import java.util.List;

/* User persistence layer interface, "operate database, based on Dao" */
public interface IUserDao {

    // Query all operations
    List<User> findAll(a);
}
Copy the code

Step 3: Create Mybatis master configuration file SQLmapConifg.xml

<?xml version="1.0" encoding="UTF-8"? >

      

<! Mybatis master configuration file -->
<configuration>
    <! -- Configure the environment -->
    <environments default="mysql"><! -- There is no rule on the name, here is the definition of the name -->
        <! Mysql > create mysql
        <environment id="mysql">  <! -- Same name as above -->
            <transactionManager type="JDBC"></transactionManager>
            <! The connection pool can take three values -->
            <dataSource type="POOLED"><! --POOLED -->
                <! -- Configure 4 basic information for connecting to database -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>

            </dataSource>
        </environment>
    </environments>

    <! -- Specify the location of the mapping configuration file, which is a separate configuration file for each DAO.
    <mappers>
        <! For IUserDao file, write the corresponding XML configuration file in Resources.
        <mapper resource="com/itheima/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>
Copy the code

Step 4: Create the mapping configuration file iUserdao.xml

<?xml version="1.0" encoding="UTF-8"? >

      

<! The value of the namespace attribute must be the fully qualified class name of the DAO interface.
<mapper namespace="com.itheima.dao.IUserDao">
    <! -->
    <! ResultType is the return type of the dao interface.
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user  <! -->
    </select>
</mapper>
Copy the code

Appendix Supplement:

1. Import the SQL file (mybatisdb.sql) and modify the required data in the related file

2. Add the log file log4j.properties to the project

2.2 Precautions for Environment Construction:

1. Create iUserdao.xml with the same name as iUserdao.java.

In Mybatis, it also calls the operation interface name and mapping file of persistence layer: Mapper

So: the IUserDao is the same as the IUserMapper

2. When creating a directory in IDEA, it is different from a package

When the package is created: com.itheima.dao It is a tertiary structure

When the directory is created: com.itheima.dao is a tier 1 directory

3. The mapping configuration file location of MyBatis must be the same as the package structure of the DAO interface

4. The namespace attribute of the mapper tag in the mapping configuration file must be the fully qualified class name of the DAO interface

Don’t forget the way myBatis is told which entity class to encapsulate in the mapping configuration: specify the fully qualified class name of the entity class

5. Mapping configuration file operation configuration (SELECT), the value of the ID attribute must be the dao interface method name

3. Mybatis Introduction case (three cases based on the previous operation)

3.1 Create a MybatisTest. Java based on the previous steps

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
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.InputStream;
import java.util.List;

/* Mybatis */
public class MybatisTest {

    /* Get started */
    public static void main(String[] args) throws Exception{
        //1. Read configuration file (in this case, connect database)
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // create SqlSessionFactory
                /*SqlSessionFactory is an interface that can not be new. Mybatis provides an SqlSessionFactoryBuilder, which can be new directly. How to parse the configuration file and how to encapsulate it is none of our business
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3. Use the factory to produce SqlSession objects
        SqlSession session = factory.openSession();
        //4. Create a proxy object for the Dao interface (Dao implementation) using SqlSession
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5. Use proxy objects to execute methods
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
        //6. Release resourcessession.close(); in.close(); }}Copy the code

3.2. Annotation-based introduction to Mybatis

1. Remove the iUserdao.xml file, annotate the DAO interface methods with @SELECT annotations, and specify Sql statements

2. During mapper configuration in SQLmapConfig. XML, use the class attribute to specify the fully qualified class name of the DAO interface

3.3 MyBatis does not use XML and annotation configuration, write its own DAO implementation class

In the actual development, we are as simple as possible, so we use the way of not writing DAO implementation classes.

Whether you use XML or annotation configuration.

However, Mybatis supports writing dao implementation classes.

1. Create UserDaoImpl. Java

package com.itheima.dao.impl;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDaoImpl implements IUserDao {

    // Define a variable that holds the session object
    private SqlSessionFactory factory;

    // Make sure factory has a value
    // Override the default constructor, which means there is no default constructor, so when it is used, it must pass in a factory
    public UserDaoImpl(SqlSessionFactory factory){
        this.factory = factory;
    }

    @Override / / implementation class
    public List<User> findAll(a) {
        //1. Use factory to create SqlSession object,
        SqlSession session = factory.openSession();
        //2. Use session to query all methods
        // Fill in the namespace.id corresponding to the XML configuration file
        List<User> users =  session.selectList("com.itheima.dao.IUserDao.findAll");
        session.close();  // Close when finished
        //3. Return the query result
        returnusers; }}Copy the code

2. Modify MybatisTest. Java

3.4 Analysis of the Query All function

4. Customize myBatis framework (the main purpose is to understand the implementation details in MyBatis)

4.1 Custom Mybatis analysis

4.2 Customizing Mybatis (XML and Annotations are available)
4.2.0 Delete mybatis configuration from POM.xml (delete part in figure)

4.2.1 After deletion, create classes and interfaces according to the missing MybatisTest test class

1.Resources.java

2.SqlSession.java

3.SqlSessionFactory.java

4.SqlSessionFactoryBuilder.java

4.2.2. For the SqlSessionFactoryBuilder is Java build

1. Create the utility class XMLConfigBuilder under utils to parse the configuration file xmlConfigBuilder.java

2. Import the coordinates of dom4j and Jaxen in pom.xml ———-> dom4j and xpath, the technologies used to parse configuration files

<dependency>
	<groupId>dom4j</groupId>
	<artifactId>dom4j</artifactId>
	<version>1.6.1</version>
 </dependency>

<dependency>
	<groupId>jaxen</groupId>
	<artifactId>jaxen</artifactId>
	<version>1.1.6</version>
</dependency>
Copy the code

3. Create the corresponding class for the error in xmlConfigBuilder.java

Configuration. The Java Mapper. Java, Select JavaCopy the code

Behind the front two files are XML configuration, one is the annotation configuration, can put XMLConfigBuilder. About annotations in Java configuration code commented out first, to study the XML configuration, and then learn annotation configuration, or two together to learn, easy to mix

4. There are no errors in xmlConfigBuilder.java after the previous operations are complete.

At this point, to the SqlSessionFactoryBuilder is. Java build

5. With Config, there is still no factory, and now the factory is an interface, so create an implementation class for the factory interface

6. If there is a factory, there is a session

The above operation:

SqlSessionFactoryBuilder has == builder ==,

The DefaultSqlSessionFactory(CFG) builder builds the == factory ==

DefaultSqlSession(CFG) factory produces a ==SqlSession==

Files to add:

MapperProxy.java
DataSourcesUtil.java
Executor.java
Copy the code

To complete the above, run the main method of MybatisTest. Java to get the result

Explain in plain English

We need to finally implement the query all, and all query functions in the tool class, and finally call this tool class.

B: Then when can they be used? When creating Dao implementation class enhancements,

Thirdly, when will it be strengthened? Create the Dao implementation class (a call to MapperProxy) when creating the proxy object,

Invoke is used to enhance a method, which is essentially a selectList method,

MapperProxy finds the statement to execute and encapsulates the result

Why look for executed statements and encapsulated results?

① The result of getMappers can be seen from the contents of setMappers

MapperProxy(Map<String,Mapper> mappers,Connection conn)

The first argument to is also noticeable

Position. where do I find it? Look in the configuration file,

A file is also taken from a configuration file. The configuration file is read by XMLConfigBuilder, and when it’s read, it needs to be saved,

How to save it? The Configuration object is used

Select. Java is an annotation configuration, and 4.2.2 is about XML configuration, so select. Java is not covered yet.

MapperProxy.java
DataSourcesUtil.java
Executor.java
Copy the code

8. The previous 4.2.2 has completed parts 1 to 7, that is, the XML configuration part. Next, it will be changed to annotation configuration

Sqlmapconfig. XML file, change to annotation configuration

The iUserdao.java file is modified

To add the select.java file, if you have added it before, you do not need to add select.java again

To complete the above, run the main method of MybatisTest. Java to get the result


Article part code file download link: download.csdn.net/download/qq…