How mybaits is written and what it does

1. Create database and table structure

reate database mybatis_demo;

use mybatis_demo;

CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'老王','2018-02-27
17:47:08','男','北京'),(2,'熊大','2018-03-02 15:09:37','女','上海'),(3,'熊二','2018-03-04
11:34:34','女','深圳'),(4,'光头强','2018-03-04 12:04:06','男','广州');

2. mybatis writing

1. Create a maven project and create a Java project.

2. Import coordinates

1. Introduce the coordinates of MyBatis version 3.4.5

2. Introduce the jar package driven by MySQL, version 5.1.6

3. Introduce the jar package of Junit unit test

4. Import the jar package of log4j, version 1.2.12 (need to import the configuration file of log4j.properties)

<dependencies>
<!--mybatis核心包--> 
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

3. Write the entity class of User, and use the packaging type as much as possible for the attributes. The specific code is as follows

package com.qcby.entity;
import java.io.Serializable;
import java.util.Date;
public class User  {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

4. Write the interface and method of UserDao

package com.qcby.dao;

import com.qcby.entity.User;

import java.util.List;

/**
 * 查询所有用户
 */
public interface UserDao {
    public List<User> findAll();
}

5. In the resources directory, create a mapper folder. Write the configuration file of UserDao.xml and import the constraint 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.qcby.dao.UserDao">
    <select id="findAll" resultType="com.qcby.entity.User">
        select * from user
    </select>
</mapper>

(1) mapper namespace="com.qcby.dao.UserDao", called the namespace, indicating the method of findingAll in the UserDao interface in the future.

(2) The name of the method in the UserDao interface written by the id attribute in select id="findAll" is fixed.

(3) resultType="com.qcby.entity.User" indicates the return value type of the findAll method.

6. Configure related xml files

Write the main configuration file, create a configuration file of SqlMapConfig.xml in the resources directory (in fact, the name can be arbitrary), and import the corresponding

constraints, write the main configuration file. (Shortcut key ctrl+shift+/: quick note)

<?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="mysql">
        <environment id="mysql">
            <!--配置事务的类型,使用本地事务策略-->
            <transactionManager type="JDBC"></transactionManager>
            <!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/>
                <property name="username" value="root"/>
                <property name="password" value="2020"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserDao.xml"></mapper>
    </mappers>
</configuration>

7 Create a test class

  /**
     * 测试查询所有的方法
     */
    @Test
    public void findAll() throws IOException {
         List<User> users = mapper.findAll();
        for (User user:users) {
            System.out.println(user.toString());
        }
    }

Role: mybatis is an excellent java-based persistence layer framework, which encapsulates jdbc inside, so that developers only need to pay attention to the sql statement itself, instead of spending energy to deal with complicated processes such as loading drivers, creating connections, and creating statements.
Mybatis configures the various statements to be executed through xml or annotations, and generates the final executed sql statement through the mapping between the java object and the dynamic parameters of sql in the statement. Finally, the mybatis framework executes the sql and maps the result to a java object and return.
The ORM idea is adopted to solve the problem of entity and database mapping, jdbc is encapsulated, and the underlying access details of jdbc api are shielded, so that we can complete the persistence operation of the database without dealing with jdbc api.
 

Guess you like

Origin blog.csdn.net/cang_ling/article/details/126465416