Home >Backend Development >PHP Tutorial >Use of Mybatis (mapper interface method)

Use of Mybatis (mapper interface method)

赶牛上岸
赶牛上岸Original
2018-03-06 16:15:007032browse

Using the Mapper interface, there is no need to write an interface implementation class, and the database operation can be completed directly, which is simple and convenient. In order to help everyone learn the Mapper interface better, the editor has summarized some knowledge points about the Mapper interface, hoping to help those in need.

First go to the structure diagram:
Use of Mybatis (mapper interface method)
The following is the specific code:
1. User.java

实体类中的的get/set方法以及构造方法及toString方法就不贴了
public class User {    
    private int id;    
    private String name;    
    private int age;
}

2. UserMapper.java
This is the mapper interface, and the idea of ​​interface-oriented programming is still very important. It is also the most important part of this blog post.

The interface definition has the following characteristics:

  1. The Mapper interface method name has the same name as the id of each sql defined in UserMapper.xml.

  2. The input parameter type of the Mapper interface method is the same as the parameterType type of sql defined in UserMapper.xml.

  3. The return type of the Mapper interface is the same as the resultType of sql defined in UserMapper.xml

Pay attention to the method of creating the table, There is annotation @Param

package com.mi.mapper;import org.apache.ibatis.annotations.Param;import com.mi.beans.User;public interface UserMapper {
    void createTable (@Param("tableName") String tableName);    void add(User user);    void del(int id);    void update(User user);
    User getUser(int id);
    User[] list();
}

3. userMappers.xml
Need to pay attention here
1. The namespace of the xml file must be written as mapper interface The path is as follows.

<mapper namespace="com.mi.mapper.UserMapper">

2. When writing the statement to dynamically create a table, write ${tableName} instead of #{}. Click to view the difference between the two

create table ${tableName}...

The following is the complete code: including table creation, CRUD

<mapper namespace="com.mi.mapper.UserMapper">
    
    
        create table ${tableName} (id int primary key auto_increment,name varchar(20),age int)    
    
    
        insert into t_user(name,age) value(#{name},#{age})    
    
    
        delete from t_user where id = #{id}    
    
    
        update t_user set name=#{name},age=#{age} where id=#{id}    
    
    
    
    

4, conf.xml
Two things need to be configured here

  • Configuration JDBC connection

  • Configuration mapper.xml

<?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" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
        <!-- 注册userMapper.xml文件 -->
    <mappers>
        <mapper resource="com/mi/mapping/userMappers.xml"/>
    </mappers></configuration>

5. SqlSessionUtil.java
I write here A tool class is created, the main purpose is to get the sqlSession, because every time the database is operated in the future, it needs to be written once, so it is encapsulated once.

package com.mi.util;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.
session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionUtil 
{
      public static SqlSession getSqlSession() throws Exception{
      String resource = "conf.xml";
      //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
      InputStream is = Resources.getResourceAsStream(resource);
      //构建sqlSession的工厂
      SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
      //创建能执行映射文件中sql的sqlSession
      SqlSession sqlSession = sessionFactory.openSession();
      return sqlSession;
   }
}

6. MyTest.java
This is a test class. Through the above tool class sqlSession, the most important thing is the following sentence

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

MyBatis implements the mapper interface through dynamic proxy. After that, it will be easy to handle. Execute the interface Just use the prepared method.
Be careful not to forget sqlSession.commit() and sqlSession.close(). Otherwise, although no error will be reported during execution, there will be no changes in the database.

这里我只执行了创建表的方法.
package com.mi.test;import org.apache.ibatis.session.SqlSession;import com.mi.beans.User;import com.mi.mapper.UserMapper;
import com.mi.util.SqlSessionUtil;public class MyTest {
    public static void main(String[] args) throws Exception {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.createTable("t_user");
        sqlSession.commit();
        sqlSession.close();
    }
}

         

Using the Mapper interface, there is no need to write an interface implementation class, and the database operation can be completed directly, which is simple and convenient.
First go to the structure diagram:
Use of Mybatis (mapper interface method)
The following is the specific code:
1. User.java

实体类中的的get/set方法以及构造方法及toString方法就不贴了public class User {    private int id;    private String name;    private int age;

2. UserMapper .java
This is the mapper interface, and the idea of ​​interface-oriented programming is still very important. It is also the most important part of this blog post.

The interface definition has the following characteristics:

  1. The Mapper interface method name has the same name as the id of each sql defined in UserMapper.xml.

  2. The input parameter type of the Mapper interface method is the same as the parameterType type of sql defined in UserMapper.xml.

  3. The return type of the Mapper interface is the same as the resultType of sql defined in UserMapper.xml

Pay attention to the method of creating the table, There is annotation @Param

package com.mi.mapper;import org.apache.ibatis.annotations.Param;import com.mi.beans.User;public interface UserMapper {
    void createTable (@Param("tableName") String tableName);    void add(User user);    void del(int id);    void update(User user);
    User getUser(int id);
    User[] list();
}

3. userMappers.xml
Need to pay attention here
1. The namespace of the xml file must be written as mapper interface The path is as follows.

<mapper namespace="com.mi.mapper.UserMapper">

2. When writing the statement to dynamically create a table, write ${tableName} instead of #{}. Click to view the difference between the two

create table ${tableName}...

The following is the complete code: including table creation, CRUD

<mapper namespace="com.mi.mapper.UserMapper">
    
    
        create table ${tableName} (id int primary key auto_increment,name varchar(20),age int)    
    
    
    
        insert into t_user(name,age) value(#{name},#{age})    
    
    
    
        delete from t_user where id = #{id}
     
    
    
        update t_user set name=#{name},age=#{age} where id=#{id}    
    
    
    
    
    

4, conf.xml
Two things need to be configured here

  • Configuration JDBC connection

  • Configuration mapper.xml

<?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" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
        <!-- 注册userMapper.xml文件      -->
    <mappers>
        <mapper resource="com/mi/mapping/userMappers.xml"/>
    </mappers></configuration>

5. SqlSessionUtil.java
I write here A tool class is created, the main purpose is to get the sqlSession, because every time the database is operated in the future, it needs to be written once, so it is encapsulated once.

package com.mi.util;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionUtil 
{
      public static SqlSession getSqlSession() throws Exception{
        String resource = "conf.xml";
         //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream is = Resources.getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
      //创建能执行映射文件中sql的sqlSession
        SqlSession sqlSession = sessionFactory.openSession();
        return sqlSession;
    }
}

6. MyTest.java
This is a test class. Through the above tool class sqlSession, the most important thing is the following sentence

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

MyBatis implements the mapper interface through dynamic proxy. After that, it will be easy to handle. Execute the interface Just use the prepared method.
Be careful not to forget sqlSession.commit() and sqlSession.close(). Otherwise, although no error will be reported during execution, there will be no changes in the database.

这里我只执行了创建表的方法.
package com.mi.test;import org.apache.ibatis.session.SqlSession;import com.mi.beans.User;import com.mi.mapper.UserMapper;
import com.mi.util.SqlSessionUtil;public class MyTest {
    public static void main(String[] args) throws Exception {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.createTable("t_user");
        sqlSession.commit();
        sqlSession.close();
    }
}

Related recommendations:

Mybatis paging plug-in pageHelper example detailed explanation

##Oracle combines Mybatis to implement 10 pieces of data from the table

Spring Boot, Mybatis, Redis quickly build modern Web projects


The above is the detailed content of Use of Mybatis (mapper interface method). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn