Mybatis start



A persistence layer framework that simplifies SQL operations. Development only needs to focus on specific SQL statements

Traditional JDBC: 1 Operation SQL 2 Operate connection, station (an object that sends SQL to the database), resultset, etc

ORM framework: object relationship matching, which transforms the data in relational database into objects in object-oriented program

Hibernate (automatic SQL) and mybatis (custom SQL)

1. Introducing dependency in POM

Mybais only needs this dependency to complete
However, it is necessary to operate the database, so the connection database driver is introduced
Add a dependency of the test class for testing


Write the mybatis core configuration file (put it in the resource directory)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
<!--configuration core file-->

    <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/hualian?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>

    <!-- Set mapper XML is important to register in the core configuration file of mybatis!! -- > >
        <mapper resource="com/gxa/hualian/mapper/UserMapper.xml"/>

3. Introduce mapper in POM xml

In order to load the XML file of mapper under the Java folder

4. Write java code



public class User implements Serializable {

    private Long id;
    private String name;
    private Integer points;
    private String phone;
    private Timestamp regTime;

    public User(Long id, String name, Integer points, String phone, Timestamp regTime) { = id; = name;
        this.points = points; = phone;
        this.regTime = regTime;

    public User() {


public interface UserMapper {

    void   add(User user);

    void deleteById(Long id);

    void  update(User user);

    List<Map> selectAll();


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN" "">
<mapper namespace="com.gxa.hualian.mapper.UserMapper">
    <!-- Add, delete, modify and query SQL -- >
    <insert id="add" parameterType="com.gxa.hualian.pojo.User">
        insert into `user` (`name`,`phone`,`regTime`) values (#{name},#{phone},#{regTime})

    <delete id="deleteById" parameterType="long">
        delete from `user` where id=#{id}

    <update id="update" parameterType="com.gxa.hualian.pojo.User">
        update `user` set `name`=#{name},`phone`=#{phone},`regTime`=#{regTime}

    <select id="selectAll" resultType="java.util.Map">
        select * from `user`


public class TestUser {

    UserMapper mapper=null;
    SqlSession sqlSession = null;
    //To get sqlsession
    public void init() throws IOException {
        //Resources: a file stream reading tool provided by mybatis
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
        //Instantiate a builder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //Get a factory object through builder
        SqlSessionFactory factory =;
        //Get the session object through opensession. The default is to submit the transaction manually
        //Sqlsession provides all the methods required to execute SQL commands in the database
        sqlSession= factory.openSession();

        //Get the proxy object of mapper interface
        mapper= sqlSession.getMapper(UserMapper.class);

    public void add(){

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User = new user ("test", 0, "7898", timestamp);

        //Method for obtaining proxy object readjustment

        //Sqlsession's own methods also have additions, deletions, modifications and queries. The statement parameter (the first parameter) should be consistent with the method name in the interface
        sqlSession.insert("add", user);


    public void deleteById(){

    public void update(){
        Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
        User user1 = new user (44l, "test 4", 0, "+ 65 + 6565 +", timestamp1);
        sqlSession.update("update", user1);

    public void selectAll(){

        List<Map> maps = mapper.selectAll();
        for (Map map : maps) {


Pit encountered:

1. When there is no spring management, you need to create your own sqlsession if you want the mapper object

2. The XML file is not imported into POM, and the report cannot find usermapper XML error

Label configuration resolution:

Mappers: mapper, usermapper The configuration in the XML file is mapped to a specific mapper XML file

<!-- Set mapper XML is registered in the core configuration file of mybatis -- >
        <mapper resource="com/gxa/hualian/mapper/UserMapper.xml"/>

Namespace: used to bind Dao interface

<mapper namespace="">

Environments: the environment configuration collection can configure multiple databases

Environment: specific implementation of environment configuration

Connection pool: the server creates multiple connections to the database at one time and saves multiple connections in one connection pool object. The next time there is a request to operate the database, it directly obtains a connection from the connection pool and continues to put it back into the connection pool instead of closing it after use, which can save the resources of creating / releasing connections

//Default: development mode work mode
<environments default="development">
 //ID: Specifies the unique ID of the current environment
        <environment id="development">
//Transactionmanager: transaction manager type: JDBC - using JDBC's native transaction management method, both commit and rollback need to be manually executed
            <transactionManager type="JDBC"/>
//Using datasource: pooled datasource
            <dataSource type="POOLED">
//Property: property, connection driver, URL, user name and password
                <property name="driver" value="com.mysql.jdbc.Driver"/>
//Usessl: SSL protocol is used to ensure data security and correctness. The default is true
                <property name="url" value="jdbc:mysql://localhost:3306/hualian?useSSL=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>