MyBatis3.x Idea building

Keywords: Java Apache log4j Mybatis JDBC

MyBatis was apache An open source project of iBatis In 2010, the project was migrated from apache software foundation to google code and renamed MyBatis. Moved to Github in November 2013.

As an excellent orm framework, MyBatis is often compared with Hibernate. As a popular MyBatis, it avoids almost all JDBC code, manual parameter setting and result set acquisition. Next let's see how to build a MyBaits project.
Because idea does not support the automatic building of mybatis, we need to manually import some jar packages

Jar package to prepare

Mybatis-3.4.6.jar the main body of mybatis
mysql-connector-java-5.1.46.jar
log4j-1.2.17 for printing log

There are two ways to build Mybatis. Let's look at XML first

XML mode

1. Mybatis-configuration.xml

mybatis-configuration.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>
    <! -- import profile -- >
    <properties resource="db.properties"/>
    Set log4j for printing -- >
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <! -- set runtime environment -- >
    <! -- mybatis allows multiple runtime environments -- >
    <environments default="development">
        <environment id="development">
            <! -- transactionmanager transaction manager -- >
            <! -- set the transaction management mode as JDBC -- >
            <transactionManager type="JDBC"/>
            <! -- data source connection pool -- >
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <! -- import mapping file -- >
    <mappers>
        <mapper resource="model/UserMapper.xml"/>
    </mappers>
</configuration>

2.User.java and UserMapper.xml

User.java

package model;

/**
 * Created by Administrator on 2018/10/31.
 */
public class User {

    private int id;

    private String username;

    private String nickname;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", nickname='" + nickname + '\'' +
                '}';
    }
}

UserMapper.xml

<?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">
<!-- Namespace takes itself a name as the unique identifier of the call-->
<mapper namespace="model.UserMapper">
    <!-- id sql Sentence id Use namespace on call+sqlid Method -->
    <!-- parameterType Parameter type -->
    <!-- resultType return type -->
    <select id="selectUserById" parameterType="int" resultType="model.User">
        <!-- For parameter injection#Or $- >
        <!-- #It is a placeholder. When precompiling, use "placeholder" to prevent sql injection problems -- >
        <!-- $Is a connector.,analysis sql Use variable substitution directly when,May cause sql Injection problem -->
        <!-- #And $are equivalent to preparedStatement and statement -- >
        <!-- In general,Can use#Don't use $-- >
        select id,username,nickname from user where id = #{id}
    </select>

</mapper>

3.db.properties and log4j.properties

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
user=root
password=root

log4j.properties

log4j.rootLogger=DEBUG, stdout    

log4j.appender.stdout=org.apache.log4j.ConsoleAppender    
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout    
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n    

#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.R.File=../logs/service.log
#log4j.appender.R.layout=org.apache.log4j.PatternLayout
#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#log4j.logger.com.ibatis = debug
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug
#log4j.logger.java.sql.Connection = debug
log4j.logger.java.sql.Statement = debug    
log4j.logger.java.sql.PreparedStatement = debug    
log4j.logger.java.sql.ResultSet =debug   

4. Test it

Main.java

import model.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 java.io.IOException;
import java.io.Reader;

public class Main {

    public static void main(String[] args) throws IOException {
        //xml mode
        //Define the path of the configuration file for mybatis
        String resource = "mybatis_config.xml";
        //Convert configuration file to reader
        Reader reader = Resources.getResourceAsReader(resource);
        //Using sqlsessionfactorybuilder to load the configuration file
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //Get sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = sqlSession.selectOne("model.UserMapper.selectUserById",1);
        System.out.println(user);
    }
}

Finally, take a look at the output of the console

[service] 2018-10-31 16:59:55,875 - org.apache.ibatis.logging.LogFactory -0    [main] DEBUG org.apache.ibatis.logging.LogFactory  - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    [service] 2018-10-31 16:59:56,047 - org.apache.ibatis.logging.LogFactory -172  [main] DEBUG org.apache.ibatis.logging.LogFactory  - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,075 - org.apache.ibatis.datasource.pooled.PooledDataSource -200  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
    [service] 2018-10-31 16:59:56,207 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -332  [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction  - Opening JDBC Connection
    [service] 2018-10-31 16:59:56,541 - org.apache.ibatis.datasource.pooled.PooledDataSource -666  [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource  - Created connection 836514715.
    [service] 2018-10-31 16:59:56,541 - org.apache.ibatis.transaction.jdbc.JdbcTransaction -666  [main] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@31dc339b]
    [service] 2018-10-31 16:59:56,543 - model.UserMapper.selectUserById -668  [main] DEBUG model.UserMapper.selectUserById  - ==>  Preparing: select id,username,nickname from user where id = ? 
    [service] 2018-10-31 16:59:56,607 - model.UserMapper.selectUserById -732  [main] DEBUG model.UserMapper.selectUserById  - ==> Parameters: 1(Integer)
    [service] 2018-10-31 16:59:56,640 - model.UserMapper.selectUserById -765  [main] DEBUG model.UserMapper.selectUserById  - <==      Total: 1
    User{id=1, username='Da Peng Zhao', nickname='Death train'}

You can see that the sql statements and query results are out, and mybatis is built in xml mode.

Posted by johnie on Sun, 08 Dec 2019 19:46:40 -0800