Mybatis environment configuration and use

What is Mybatis?

MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mappings. MyBatis eliminates almost all JDBC code and manual setting of parameters and retrieval of result sets. MyBatis uses simple XML or annotations for configuration and primitive mapping, mapping interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) to records in the database.

Configure the Mybatis environment

Create a Javaweb project

For those who are not clear about this part, you can check my other blog to create your own first Javaweb project

project code

  • User.java
package cn.newtol.pojo.model;

/**
 * @Author: REN
 * @Description:
 * @Date: Created in 22:45 2018/4/26
 */
public class User {
    private int id;
    private String name;
    private String phone;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}
  • IUser.java
package cn.newtol.mybatis.dao;

import cn.newtol.mybatis.pojo.User;

/**
 * @Author: REN
 * @Description:
 * @Date: Created in 22:55 2018/4/26
 */
public interface IUser {
    public User getUser();
}
  • MyselfDefineDataSourceFactory .java
package cn.newtol.mybatis.util;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

public class MyselfDefineDataSourceFactory extends UnpooledDataSourceFactory {
    public MyselfDefineDataSourceFactory() {
        this.dataSource = new DruidDataSource();
    }
}
  • SqlSessionFactoryUtil.java
package cn.newtol.mybatis.util;
/**
 * @Author: REN
 * @Description:
 * @Date: Created in 23:25 2018/3/14
 */


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class SqlSessionFactoryUtil {
    //首先创建静态成员变量sqlSessionFactory,静态变量被所有的对象所共享。
    public static SqlSessionFactory sqlSessionFactory = null;
    public static SqlSessionFactory getSqlSessionFactory() {
        //如果sqlSessionFactory没有被创建就读取全局配置文件,假如已经被创建过了,就使用已经存在的sqlsessionfactory。
        //这样就有了单例模式的效果
        if(sqlSessionFactory==null){
            String resource = "Configure.xml";
            try {
                Reader reader = Resources.getResourceAsReader(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }
}
  • Main function test.java
package cn.newtol.mybatis;

import cn.newtol.mybatis.dao.IUser;
import cn.newtol.mybatis.pojo.User;
import cn.newtol.mybatis.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

/**
 * @Author: REN
 * @Description:
 * @Date: Created in 23:37 2018/4/26
 */
public class test {

        public static void main(String[] args) {
            SqlSessionFactoryUtil sqlSessionFactoryUtil = null;
            SqlSession session = sqlSessionFactoryUtil.getSqlSessionFactory().openSession();
            try {
                IUser iuser = session.getMapper(IUser.class);
                User u = iuser.getUser();
                System.out.println("id:"+u.getId()+"----"+"name:"+u.getName()+"----"+"phone:"+u.getPhone());
            }finally {
                session.close();
            }

        }
}
  • User.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">
<mapper namespace="cn.newtol.mybatis.dao.IUser">
    <!--管理员登录-->
    <select id="getUser"  resultType="User">
        select * from `user`
    </select>
</mapper>
  • Configure.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>
    <properties resource="jdbc.properties"></properties>

    <typeAliases>
        <typeAlias alias="User" type="cn.newtol.mybatis.pojo.User" />
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="cn.newtol.mybatis.util.MyselfDefineDataSourceFactory">
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />
                <property name="driverClass" value="${jdbc.driver}"/>

                <property name="initialSize" value="${jdbc.initialSize}" />
                <property name="minIdle" value="${jdbc.minIdle}" />
                <property name="maxActive" value="${jdbc.maxActive}" />
                <property name="maxWait" value="${jdbc.maxWait}" />
                <!-- 超过时间限制是否回收 -->
                <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
                <!-- 超过时间限制多长; -->
                <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
                <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
                <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
                <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
                <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
                <!-- 用来检测连接是否有效的sql,要求是一个查询语句-->
                <property name="validationQuery" value="${jdbc.validationQuery}" />
                <!-- 申请连接的时候检测 -->
                <property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
                <!-- 申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
                <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
                <!-- 归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 -->
                <property name="testOnReturn" value="${jdbc.testOnReturn}" />
            </dataSource>
        </environment>

    </environments>

    <mappers>
        <mapper resource="Mapper/User.xml" />
    </mappers>
</configuration>
  • jdbc.properties
jdbc.url=jdbc:mysql://127.0.0.1/你的数据库名?characterEncoding=utf-8
jdbc.username=数据库账号
jdbc.password=数据库密码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.initialSize=1
jdbc.minIdle=1
jdbc.maxActive=20
jdbc.maxWait=60000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=180
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 1 
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
  • log4j.properties (no modification required)
log4j.rootCategory=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.logger.com.jege.mybatis=TRACE

# 设置日志输出类型 , 为文件类型

log4j.appender.R= org.apache.log4j.FileAppender 

# 设置日志文件的位置

log4j.appender.R.file=../logs/cheer_vote.log

# 每次在文件尾写入新的日志信息

log4j.appender.R.Append= true 

# 日志输出信息格式类型

log4j.appender.R.layout= org.apache.log4j.PatternLayout 

# 日志输出信息格式为 换行、日期、优先级、 [ 全类名 ] 、日志信息、换行

log4j.appender.R.layout.ConversionPattern= %n%d%p [%l] %m%n
  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.newtol</groupId>
  <artifactId>testMybatis</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>testMybatis Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.11.0</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.12</version>
    </dependency>
    <dependency>
      <groupId>commons-pool</groupId>
      <artifactId>commons-pool</artifactId>
      <version>1.6</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.13</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>testMybatis</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

project directory

write picture description here

Create data table

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL DEFAULT '',
  `phone` varchar(16) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'rock', '13800009988');

Then just run the main function of test.java and see the following results:
write picture description here

Then congratulations, the mybaitis environment is successfully configured, the connection pool uses druid, and this code can be used directly for project development

Github address

Source code download address

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325162054&siteId=291194637