MyBatis基础:MyBatis入门(1)

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
posted @ 2017-08-15 17:11  libingql  阅读(291)  评论(0编辑  收藏  举报