How to use MyBatis

Posted by webrajesh on Fri, 14 Jan 2022 03:30:50 +0100

What is MyBatis?

MyBatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (plain ordinary Java objects) into records in the database.

ORMapping: Object Relationship Mapping
Object refers to object-oriented
Relational refers to a relational database
With the mapping from Java to MySQL, developers can manage the database with the idea of object-oriented.

How to use?

  • New Maven project, POM xml
 <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
  • New data table
use mybatis;
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
  • Create an entity class Account corresponding to the data table
package com.chen.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private long id;
    private String username;
    private String password;
    private int age;
}
  • Create the configuration file config. For MyBatis XML, the file name can be customized
<?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>

    <!-- to configure MyBatis Operation environment -->
    <environments default="development">
        <environment id="development">
            <!-- to configure JDBC Affairs Management -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED to configure JDBC Data source connection pool -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="5846028"/>
            </dataSource>
        </environment>
    </environments>

</configuration>
  • Use native interfaces

1. MyBatis framework requires developers to customize SQL messages, which are written in mapper In the XML file, in the actual development, the corresponding Mapper.xml file will be created for each entity class XML to define the SQL that manages the object data.

<?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.chen.mapper.AccountMapper">

    <insert id="save" parameterType="com.chen.entity.Account">
        insert into t_account(username,password,age) values(#{username},#{password},#{age})
    </insert>
</mapper>
  • namespace is usually set to the form of package + file name where the file is located.
  • The insert tag indicates that the add operation is performed.
  • The select tag indicates that the query operation is performed.
  • The update tag indicates that the update operation is performed.
  • The delete tag indicates that the deletion operation is performed.
  • id is the parameter needed to actually call the MyBatis method.
  • parameterType is the data type of the parameter when the corresponding method is called.

2. In the global configuration file config Register AccountMapper.xml xml

<configuration>

    <!-- to configure MyBatis Operation environment -->
    <environments default="development">
        <environment id="development">
            <!-- to configure JDBC Affairs Management -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- POOLED to configure JDBC Data source connection pool -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="5846028"/>
            </dataSource>
        </environment>
    </environments>

    <!-- register AccountMapper.xml -->
    <mappers>
        <mapper resource="com/chen/mapper/AccountMapper.xml"></mapper>
    </mappers>

</configuration>

3. Call the native interface of MyBatis to perform the add operation.

package com.chen.test;

import com.chen.entity.Account;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class Test {

    public static void main(String[] args) {
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        String statement = "com.chen.mapper.AccountMapper.save";
        Account account = new Account(1L,"Zhang San","123456",18);
        sqlSession.insert(statement,account);
        sqlSession.commit();
        sqlSession.close();
    }
}
  • Implement custom interface through Mapper proxy

  • Customize the interface and define relevant business methods.

  • Write mapper corresponding to the method xml.

1. Custom interface

package com.chen.repository;

import com.chen.entity.Account;

import java.util.List;

public interface AccountRepository {

    public int save(Account account);
    public int update(Account account);
    public int deleteById(long id);
    public List<Account> findAll();
    public Account findById(long id);
}

2. Create Mapper.xml corresponding to the interface XML to define the SQL message corresponding to the interface method.

The statement tab can select insert, delete, update and select according to the business executed by SQL.
The MyBatis framework will automatically create the agent object of the interface implementation class according to the rules.

Rules:

  • Mapper. namespace in XML is the full class name of the interface.
  • Mapper. The id of the statement in XML is the corresponding method name in the interface.
  • Mapper. The parameterType of the statement in XML is consistent with the parameter type of the corresponding method in the interface.
  • Mapper. The resultType of the statement in XML is consistent with the return value type of the corresponding method in the interface.
<?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.chen.repository.AccountRepository">
<insert id="save" parameterType="com.chen.entity.Account">
insert into t_account(username,password,age) values(#{username},#{password},#{age})
</insert>

<update id="update" parameterType="com.chen.entity.Account">
update t_account set username = #{username},password = #{password},age= #{age} where id = #{id}
</update>

<delete id="deleteById" parameterType="long">
delete from t_account where id = #{id}
</delete>

<select id="findAll" resultType="com.chen.entity.Account">
select * from t_account
</select>

<select id="findById" parameterType="long"
resultType="com.chen.entity.Account">
select * from t_account where id = #{id}
</select>

</mapper>

3. In config Register AccountRepository.xml xml

 <!-- register AccountMapper.xml -->
    <mappers>
        <mapper resource="com/chen/mapper/AccountMapper.xml"></mapper>
        <mapper resource="com/chen/repository/AccountRepositoryMapper.xml"></mapper>
    </mappers>

4. Call the agent object of the interface to complete relevant business operations

public class Test2 {

    public static void main(String[] args) {
        InputStream inputStream = Test2.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Gets the agent object that implements the interface
        AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);

        //Add object
        Account account = new Account(2L,"Li Si","111111",10);
        int save = accountRepository.save(account);
        sqlSession.commit();

        //Query all objects
      /*  List<Account> list = accountRepository.findAll();
        for (Account account:list) {
            System.out.println(account);
        }
      sqlSession.close();*/

        //Query object by id
     /* Account account = accountRepository.findById(3L);
        System.out.println(account);
        sqlSession.close();*/

        //Modify object
       /* Account account = accountRepository.findById(3L);
        account.setUsername("Little red ");
        account.setPassword("147147");
        account.setAge(21);
        int update = accountRepository.update(account);
        sqlSession.commit();
        System.out.println(update);
        sqlSession.close();*/

       //Delete object by id
       /* int delete = accountRepository.deleteById(3L);
        System.out.println(delete);
        sqlSession.commit();*/

    }
}

In addition, there are more parameterType and resultType types

Mapper.xml

  • statement tab: select, update, delete and insert correspond to query, modify, delete and add operations respectively.
  • parameterType: parameter data type

1. Basic data type, query Account by id

<select id="findById" parameterType="long"
resultType="com.chen.entity.Account">
select * from t_account where id = #{id}
</select>

2. String type, query Account by name

<select id="findByName" parameterType="java.lang.String"
resultType="com.chen.entity.Account">
select * from t_account where username = #{username}
</select>

3. Wrapper class, query Account by id

<select id="findById2" parameterType="java.lang.Long"
resultType="com.chen.entity.Account">
select * from t_account where id = #{id}
</select>

4. Multiple parameters, query Account by name and age

<select id="findByNameAndAge" resultType="com.chen.entity.Account">
select * from t_account where username = #{arg0} and age = #{arg1}
</select>

5,Java Bean

<update id="update" parameterType="com.chen.entity.Account">
update t_account set username = #{username},password = #{password},age =
#{age} where id = #{id}
</update>
  • resultType: result type

1. Basic data type, count the total number of accounts

<select id="count" resultType="int">
select count(id) from t_account
</select>

2. Package category, count the total number of accounts

<select id="count2" resultType="java.lang.Integer">
select count(id) from t_account
</select>

3. String type. Query the name of the Account by id

<select id="findNameById" resultType="java.lang.String">
select username from t_account where id = #{id}
</select>

4,Java Bean

<select id="findById" parameterType="long"
resultType="com.chen.entity.Account">
select * from t_account where id = #{id}
</select>
  • Interface method
public interface AccountRepository {

    public int save(Account account);
    public int update(Account account);
    public int deleteById(long id);
    public List<Account> findAll();
    public Account findById(long id);
    public Account findByName(String name);
    public Account findById2(Long id);
    public Account findByNameAndAge(String name,int age);
    public int count();
    public Integer count2();
    public String findNameById(long id);
}
  • test
 public class Test2 {

    public static void main(String[] args) {
        InputStream inputStream = Test2.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Gets the agent object that implements the interface
        AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);

        //Add object
        /*Account account = new Account(2L,"Li Si "," 111111 ", 10);
        int save = accountRepository.save(account);
        sqlSession.commit();*/

        //Query all objects
      /*  List<Account> list = accountRepository.findAll();
        for (Account account:list) {
            System.out.println(account);
        }
      sqlSession.close();*/

        //Query object by id
     /* Account account = accountRepository.findById(3L);
        System.out.println(account);
        sqlSession.close();*/

        //Modify object
       /* Account account = accountRepository.findById(3L);
        account.setUsername("Little red ");
        account.setPassword("147147");
        account.setAge(21);
        int update = accountRepository.update(account);
        sqlSession.commit();
        System.out.println(update);
        sqlSession.close();*/

       //Delete object by id
       /* int delete = accountRepository.deleteById(3L);
        System.out.println(delete);
        sqlSession.commit();*/

       //String type, query Account by name
      /*  System.out.println(accountRepository.findByName("Zhang San ");*/

        //Wrapper class, query Account by id
       /* Long id = Long.parseLong("2");
        System.out.println(accountRepository.findById2(id));*/

       //Multiple parameters, query Account by name and age
       /* System.out.println(accountRepository.findByNameAndAge("Zhang San "(18));*/

        //Basic data type, which counts the total number of accounts
       /* System.out.println(accountRepository.count());*/

        //Package category, count the total number of accounts
        /*System.out.println(accountRepository.count2());*/

        //String type. Query the name of the Account by id
        System.out.println(accountRepository.findNameById(1L));
        sqlSession.close();
    }
}

Topics: Java Maven Mybatis Spring