Summary of mybaits in java framework

What is mybatis?

  1. MyBatis is an excellent persistence layer framework
  2. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java entity classes [PlainOld Java Objects, ordinary Java objects] to records in the database.
  3. Mybatis official document: http://www.mybatis.org/mybatis3/zh/index.html

Why do you need Mybatis

  1. Mybatis is to help programmers store data in the database and fetch data from the database.
  2. Traditional jdbc operations have many duplicate code blocks. For example: encapsulation when data is retrieved, database connection establishment, etc. Through the framework, duplicate code can be reduced and development efficiency can be improved.
  3. MyBatis is a semi-automated ORM framework (Object Relationship Mapping) --> Object Relationship Mapping
  4. All things can be done without Mybatis, but with it, all implementations will be easier!

Advantages of MyBatis

  1. Simple and easy to learn: itself is small and simple. Without any third-party dependencies, the simplest installation is as long as two jar files + a few sql mapping files are configured. It is easy to learn and easy to use. Through the documentation and source code, you can fully grasp its design ideas and implementation.
  2. Flexible: Mybatis does not impose any influence on the existing design of the application or database. sql is written in xml, which is convenient for unified management and optimization. All the requirements for operating the database can be met through the sql statement.
  3. Uncoupling SQL and program code: By providing a DAO layer, business logic and data access logic are separated, making the system design clearer, easier to maintain, and easier to unit test. The separation of sql and code improves maintainability.
  4. Provide xml tags, support writing dynamic sql.

The first mybatis program

  1. Prepare the data to be operated on in the database, as shown in the figure: a user table is created
    Insert picture description here

  2. Import mybatis dependency, mysql dependency and junit dependency in pom.xml

`<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>`
  1. Write the core configuration file of mybatis, including the data source (DataSource) of the database connection instance and the transaction manager (TransactionManager) that determines the scope and control method of the transaction
<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
</configuration>
  1. Write MyBatis tool class and build SqlSessionFactory from the core configuration file. Every application based on MyBatis is based on an instance of SqlSessionFactory as the core. The instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder. The SqlSessionFactoryBuilder can construct a SqlSessionFactory instance from an XML configuration file or a pre-configured Configuration instance.
public class MybatisUtils {
    
    
    private static SqlSessionFactory sqlSessionFactory;
    static {
    
    
        try{
    
    
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
             sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
    
    
            e.printStackTrace();
        }
    }
    public static SqlSession getSession()
    {
    
    
        return sqlSessionFactory.openSession();
    }
}
  1. Create entity class
public class User {
    
    
    private int id;
    private String name;
    private String pwd;

    public User(int id, String name, String pwd) {
    
    
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
}
  1. Write Mapper interface class
public interface UserMapper {
    
    
    List<User> selectUser();
    User getUserById(int id);
    int addUser(User user);
    int addUser1(Map<String, Object> map);
    void updataUser(User user);
}
  1. Write the Mapper.xml configuration file
<?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.dao.UserMapper">
    <select id="selectUser" resultType="com.domain.User">
        select * from mybatis.user
    </select>
</mapper>
  1. Write test class
 @Test
    public void test(){
    
    
        SqlSession session = MybatisUtils.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for(User user : users){
    
    
            System.out.println(user);
        }
        session.close();
    }

Note: When using Maven to build a project, static resources (including HTMl, pictures, CSS, JS and other files that do not need to interact with the database) are filtered out by default, so the Mapper.xml file will be filtered out, and manual configuration is not required. Let it filter.

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes> <include>**/*.properties</include>
                    <include>**/*.xml</include> </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

Guess you like

Origin blog.csdn.net/go_to_study/article/details/109336296