MyBatis3-示例工程

一、准备工作:

0、新建QuitStart类型POM项目(即Application),Java Build Path为JDK1.8,Java Compiler为1.8,MySQL为5.5.38,数据库使用Test。MySQL驱动为5.1.38,MyBatis版本为3.4.4。由于不是Spring项目并且不使用数据库连接池,所以不引入Tomcat的DBCP连接池。

1、在MySQL中新建数据表及添加示例数据,脚本如下:

Create TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `userAge` int(11) DEFAULT NULL,
  `userAddress` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


Insert INTO `user` VALUES ('1', 'jim', '100', 'guangdong,guangzhou');

注意:表类型应为InnoDB。

2、添加MyBatis3的依赖和MySQL的驱动依赖,POM配置如下:

        <!-- mysql-connector-java -->
        <!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!-- mybatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>

二、实现步骤:

1、项目的整体结构如下所示:

2、配置POM,配置如下:

<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>com.jsoft.testmybatis</groupId>
    <artifactId>test1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>test1</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- mysql-connector-java -->
        <!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!-- mybatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.4</version>
        </dependency>

    </dependencies>
</project>

3、新建User.java的POJOs

package com.jsoft.testmybatis.models;

public class User {

    private int id;
    private String userName;
    private String userAge;
    private String userAddress;

    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 getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

}

4、配置User.xml的SQL映射文件

<?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.jsoft.testmybatis.models.UserMapper">
    <select id="selectUserByID" parameterType="int" resultType="User">
        select * from user where id = #{id}
    </select>
</mapper>

注意:这里的namespace只是做为一个名词不是真是存在的。

5、配置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>

    <typeAliases>
        <typeAlias alias="User" type="com.jsoft.testmybatis.models.User" />
    </typeAliases>

    <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://127.0.0.1:3306/Test?serverTimezone=UTC" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/jsoft/testmybatis/models/User.xml" />
    </mappers>
    
</configuration>

6、测试代码在App.java中

package com.jsoft.testmybatis.test1;

import java.io.IOException;
import java.io.InputStream;

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 com.jsoft.testmybatis.models.User;

public class App {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("Configuration.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            User user = (User) session.selectOne("com.jsoft.testmybatis.models.UserMapper.selectUserByID", 1);
            System.out.println(user.getUserAddress());
            System.out.println(user.getUserName());
        } finally {
            session.close();
        }
    }

}

7、测试结果如下:

三、解释说明:

1.Configuration.xml是MyBatis用来建立SessionFactory用的,里面主要包含了数据库连接相关东西,还有Java类所对应的别名,比如<typeAlias alias="User" type="com.jsoft.testmybatis.models.User"/>这个别名非常重要,在具体的类的映射中,比如User.xml中resultType就是对应这里的。要保持一致,当然这里的resultType还有另外单独的定义方式。
2.  Configuration.xml里面的<mapper resource="com/jsoft/testmybatis/models/User.xml"/>是包含要映射的类的XML配置文件。
3. 在User.xml文件里面主要是定义各种SQL语句,以及这些语句的参数,以及要返回的类型等。

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/mybatis/test1

 

参考:

http://www.yihaomen.com/article/java/303.htm(注意,这个例子里面用的版本是3.2.0-SNAOPSHOT,因此不会报错,如果按照这个例子使用3.2.0版本会报错,想要解决请参考:http://www.cnblogs.com/EasonJim/p/7050312.html

 

posted @ 2017-06-19 16:21  EasonJim  阅读(786)  评论(0编辑  收藏  举报