DEV Community

Jihao Deng
Jihao Deng

Posted on

MB02 Mybatis Configuration

本篇主要讨论Mybatis的环境搭建

请配合Mybatis的参考文档使用 https://mybatis.org/mybatis-3/zh/index.html

此笔记中包含两个部分:

  • 创建用于学习新技术的maven父工程+子模块项目
  • 搭建Mybatis的学习环境、创建配置文件以及编写第一个Mybatis程序

Mybatis的环境搭建以及第一个Mybatis程序的编写

创建父工程

  • 在数据库的 hellospring 链接中创建一个表
DROP TABLE IF EXISTS `h_user`;

CREATE TABLE `h_user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `h_user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(3,'李四','987654');
Enter fullscreen mode Exit fullscreen mode
  • 创建maven项目,删除项目中自动生成的src文件夹
  • 配置[pom.xml]。添加依赖包
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

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

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode
  • 继续修改[pom.xml],在靠上的位置添加pom
<modelVersion>4.0.0</modelVersion>
<groupId>learnmybatis-01</groupId>
<artifactId>overview</artifactId>
<version>0.0.2-SNAPSHOT</version>
<packaging>pom</packaging>
<name>1</name>
<description>1</description>
Enter fullscreen mode Exit fullscreen mode

这一步是为了让该项目成为一个maven父工程,以后的子项目都添加到该工程内。

在子模块中编写第一个Mybatis项目

  • 创建子模块,也就是子项目
  • 编写配置文件[mybatis-config.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>
    <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/hellospring?useSSL=true" />
                <property name="username" value="root" />
                <property name="password" value="112358" />
            </dataSource>
        </environment>
    </environments>
</configuration>
Enter fullscreen mode Exit fullscreen mode
  • 创建util包,在里面编写Mybatis工具类,用于获取sqlSessionFactory对象
public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        // 获取SqlSessionFactory对象
        try {
            String resource = "org/mybatis/example/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 能够执行SQL的对象SqlSession
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
Enter fullscreen mode Exit fullscreen mode
  • 编写实体类(构造方法、getter、setter省略),Dao接口
public class User {
    private int id;
    private String name;
    private String pwd;
}
Enter fullscreen mode Exit fullscreen mode
public interface UserDao {
    public List<User> findAll();
}
Enter fullscreen mode Exit fullscreen mode
  • 在Dao接口的同一目录(包)下,编写Mapper配置文件[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来绑定一个Dao接口 -->
<mapper namespace="com.dale.dao.UserDao">
    <select id="findAll" resultType="com.dale.pojo.User">
        select * from h_user
    </select>
</mapper>
Enter fullscreen mode Exit fullscreen mode
  • 将写好的[UserMapper.xml]放到Mybatis的配置文件[mybatis-config.xml]中进行注册(environments标签内容省略)
<!-- 核心配置文件 -->
<configuration>
    <environments default="development">
        <!-- … -->
    </environments>

    <!-- 注册Mapper.xml -->
    <mappers>
        <mapper resource="com/dale/dao/UserMapper.xml" />
    </mappers>

</configuration>
Enter fullscreen mode Exit fullscreen mode
  • 由于maven的约定大于配置,所以[UserMapper.xml]不会自动导出到target目录中,所以需要在[pom.xml]中进行配置
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
Enter fullscreen mode Exit fullscreen mode

利用JUnit来写第一个Mybatis程序

在maven的src/test/java目录内创建JUnit测试:

@Test
public void testFirst() {

    // 获取SqlSession对象
    SqlSession ss = MybatisUtil.getSqlSession();

    // 获取Dao对象,即Mapper
    UserDao userDao = ss.getMapper(UserDao.class);

    // 执行SQL
    List<User> result = userDao.findAll();

    for(User u: result) {
        System.out.println(u.getName() + " - " + u.getId());
    }

    // 关闭SqlSession
    ss.close();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)