MyBatis基礎:MyBatis入門(1)

libingql發表於2017-08-15

1. MyBatis簡介

  MyBatis 是支援定製化 SQL、儲存過程以及高階對映的優秀的持久層框架。

  MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。

  MyBatis 可以對配置和原生Map使用簡單的 XML 或註解,將介面和 Java 的 POJOs(Plain Old Java Objects,普通的 Java物件)對映成資料庫中的記錄。

2. MyBatis框架

2.1 MyBatis下載

  MyBatis下載地址:https://github.com/mybatis/mybatis-3

  MyBatis參考文件:http://www.mybatis.org/mybatis-3/getting-started.html

            http://www.mybatis.org/mybatis-3/zh/getting-started.html

2.2 MyBatis基本構成

  MyBatis核心元件:

  ◊ SqlSessionFactoryBuilder:根據配置資訊或程式碼來生成SqlSessionFactory。

  ◊ SqlSessionFactory:生成SqlSession。

  ◊ SqlSession:傳送SQL去執行並返回結果,獲取Mapper介面。

  ◊ SQL Mapper:由一個Java介面和XML檔案(或註解)構成,提供對應的SQL和對映規則。負責傳送SQL去執行,並返回結果。

3. MyBatis快速入門

3.1 基於XML實現

  專案結構:

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>libing</groupId>
    <artifactId>com-helloworld-api</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>com-helloworld-api Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>com-helloworld-api</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/helloworld?characterEncoding=utf8
database.username=root
database.password=root
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">
<configuration>
    <properties resource="jdbc.properties" />

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${database.driver}" />
                <property name="url" value="${database.url}" />
                <property name="username" value="${database.username}" />
                <property name="password" value="${database.password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mappers/RoleMapper.xml" />
    </mappers>
</configuration>
mybatis-config.xml
log4j.rootLogger=DEBUG,stdout

log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.properties
package com.libing.helloworld.model;

public class Role {
    
    private Integer id;

    private String roleName;

    public Integer getId() {
        return id;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    
}
Role.java
package com.libing.helloworld.dao;

import java.util.List;

import com.libing.helloworld.model.Role;

public interface IRoleDao {
    
    List<Role> findAll();
    
}
IRoleDao.java
<?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.libing.helloworld.dao.IRoleDao">
    <resultMap id="baseResultMap" type="com.libing.helloworld.model.Role">
        <id property="id" column="id" />
        <result property="roleName" column="role_name" />
    </resultMap>

    <select id="findAll" resultMap="baseResultMap">
        SELECT
            id,
            role_name
        FROM
            role
        ORDER BY id ASC
    </select>
    
</mapper>
RoleMapper.xml
package com.libing.helloworld.test;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.libing.helloworld.dao.IRoleDao;
import com.libing.helloworld.model.Role;

public class RoleTest {

    SqlSession sqlSession = null;

    @Before
    public void init() {
        PropertyConfigurator.configure(RoleTest.class.getClassLoader().getResourceAsStream("log4j.properties"));
        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = RoleTest.class.getClassLoader().getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void findAll() {
        try {
            IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
            List<Role> roles = roleDao.findAll();

            Assert.assertNotNull(roles);
            Assert.assertTrue(roles.size() > 0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
    }

}
RoleTest.java

  選中RoleTest.java,右擊 | Run As | JUnit Test,檢視執行結果。

DEBUG [main] - ==>  Preparing: SELECT id, role_name FROM role ORDER BY id ASC 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 6

3.2 基於註解實現

<?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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    
    <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/helloworld?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper class="com.libing.helloworld.dao.IRoleDao" />
    </mappers>
</configuration>
package com.libing.helloworld.dao;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.libing.helloworld.model.Week;

public interface IRoleDao {
    @Select("SELECT id,role_name FROM role ORDER BY id ASC")
    List<Role> findAll();
}

3.3 mysql-connector-java 6.0.6配置

  pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

  mybatis-config.xml:

<dataSource type="POOLED">
    <property name="driver" value="com.mysql.cj.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/helloworld?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useSSL=false" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</dataSource>

  jdbc.properties:

database.driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/helloworld?serverTimezone=UTCcharacterEncoding=utf8&useSSL=false
database.username=root
database.password=root

相關文章