Mybatis dynamic SQL statements -- if, where, choose, when, otherwise, foreach

Keywords: log4j JDBC Mybatis Java

Mybatis Chinese development document download

I. if, where

Step 1: Encapsulate the mapping of database tables to User.java

package cn.lemon.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    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 --{" +
                "number=" + id +
                ", Full name='" + username + '\'' +
                ", Birthday=" + birthday +
                ", Gender='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

Step 2: Create a new persistence layer (dao) interface, IUserDao.java, to operate the database

package cn.lemon.dao;

import cn.lemon.domain.User;

import java.util.List;

public interface IUserDao {
    List<User> findByUser(User user);//Query under specified conditions
}

Step 3: Create new configuration files SqlMapConfig.xml and jdbc.properties

<?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">
<!--To configure mybatis-->
<configuration>
    <!--Configure properties, using properties files-->
    <properties resource="jdbc.properties"></properties>
    <!--Define aliases-->
    <typeAliases>
        <!--Define a single alias-->
        <!--<typeAlias type="cn.lemon.domain.User" alias="user"></typeAlias>-->
        <!--Configuration package definition alias, alias=The name of the class in the package (capitalization and lowercase are acceptable))-->
        <package name="cn.lemon.domain"></package>
    </typeAliases>
    <!--Configuration environment-->
    <environments default="mysql">
        <environment id="mysql">
            <!--Configure the type of transaction-->
            <transactionManager type="JDBC"></transactionManager>
            <!--Configure connection pool-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <!--Configuration mapping file-->
    <mappers>
        <!--Configure a single mapping file-->
        <!--<mapper resource="com/lxs/dao/IUserDao.xml"></mapper>-->
        <package name="cn.lemon.dao"></package>
    </mappers>
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///db_mybatis?serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=lemon

Step 4: Write the mapping file IUserDao.xml for the persistence layer interface (note the file path)

<?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="cn.lemon.dao.IUserDao">
    <select id="findByUser" resultType="user" parameterType="user">
        select * from user
        <where>
            <if test="username != null and username.trim() != ''">
                username like '%${username}%'
            </if>
            <if test="address != null and address.trim() != ''">
                and address like '%${address}%'
            </if>
        </where>
    </select>
</mapper>

Step 5: Copy the log file log4j.properties so that we can see the printed log in the console

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
#log4j.rootCategory=debug, CONSOLE, LOGFILE
log4j.rootCategory=debug, CONSOLE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
#log4j.appender.LOGFILE=org.apache.log4j.FileAppender
#log4j.appender.LOGFILE.File=d:\axis.log
#log4j.appender.LOGFILE.Append=true
#log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

Step 6: Test class

package cn.lemon.dao;

import cn.lemon.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class IUserDaoTest {
    private InputStream inputStream;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private IUserDao iUserDao;

    @Before//Execute this method before executing other methods
    public void before() throws Exception {
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");//Read configuration files streamwise
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//Generating mybatis factory class
        sqlSession = sqlSessionFactory.openSession(true);//Represents opening mybatis to automatically commit transactions and get Session, which is equivalent to a JDBC connection
        iUserDao = sqlSession.getMapper(IUserDao.class);//Get the mapper proxy object of mybatis
    }

    @Test
    public void findByUser(){
        User user = new User();
        user.setUsername("Plum");
        user.setAddress("Xie");
        List<User> userList = iUserDao.findByUser(user);
        for (User u : userList) {
            System.out.println(u);
        }
    }

    @After//Execute this method after executing other methods
    public void after() throws Exception {
        //sqlSession.commit();// Open automatic commit transaction
        sqlSession.close();//close resource
        inputStream.close();//close resource
    }
}

See

2. Choice, when, otherwise

    <select id="findByUser" resultType="user" parameterType="user">
        select * from user where 1 = 1
        <choose>
            <when test="username != null and username.trim() != ''">and username like '%${username}%'</when>
            <when test="address != null and address.trim() != ''">and address like '%${address}%'</when>
            <otherwise></otherwise>
        </choose>
    </select>

The effect is the same as if and where.

foreach

SQL statement: SELECT * FROM USER WHERE username LIKE '% Li%' AND address LIKE '%%%' AND AND LIKE

Step 1: Add query conditions to the entity class User.java and generate get and set methods

    private List<Integer> ids = new ArrayList<>();//Query id condition

Step 2: Write foreach

    <select id="findByUser" resultType="user" parameterType="user">
        select * from user
        <where>
            <if test="username != null and username.trim() != ''">
                username like '%${username}%'
            </if>
            <if test="address != null and address.trim() != ''">
                and address like '%${address}%'
            </if>
            <!--
            <foreach>Labels are used to traverse collections with properties:
                collection:Represents the set elements to be traversed. Be careful not to write them when you write them.#{}
                open:The beginning of a representative statement
                close:Delegate concluding section
            -->
            <if test="ids != null and ids.size > 0">
                <foreach collection="ids" open="and id in(" close=")" separator="," item="uid">
                    ${uid}
                </foreach>
            </if>
        </where>
    </select>


Step 3: Modify the test class

    @Test
    public void findByUser(){
        User user = new User();
        user.setUsername("Plum");
        user.setAddress("Xie");
        user.getIds().add(45);
        user.getIds().add(46);
        user.getIds().add(48);
        List<User> userList = iUserDao.findByUser(user);
        for (User u : userList) {
            System.out.println(u);
        }
    }

set, if

When modifying a data in a database, if you don't want to modify a column of data

Step 1: Add an update method to the IUserDao.java interface

void update(User user);

The second step:

    <update id="update" parameterType="user">
        update user
        <set>
            <if test="username != null and username.trim() != ''">
                username = #{username},
            </if>
            <if test="birthday != null">
                birthday = #{birthday},
            </if>
            <if test="sex != null and sex.trim() != ''">
                sex = #{sex},
            </if>
            <if test="address != null and address.trim() != ''">
                address = #{address}
            </if>
        </set>
        where id = #{id};
    </update>

Step 3: Test classes

    @Test
    public void update() {
        User user = new User();
        user.setUsername("Li Zong");
        //user.setBirthday(new Date());
        user.setSex("male");
        //user.setAddress("China");
        user.setId(62);
        iUserDao.update(user);
    }

Posted by moonshaden on Tue, 01 Oct 2019 16:34:40 -0700