---
title: "深入浅出Mybatis系列（一）---Mybatis入门"
author: "Alex_hyts"
date: "2016-05-04T14:02:58Z"
tags: []
categories: ["企业架构"]
slug: "mybatis-mybatis"
draft: false
lastmod: "2016-05-04T14:02:53Z"
id: 2295779
url: "https://alex4java.iteye.com/blog/2295779"
---

[深入浅出Mybatis系列（一）---Mybatis入](http://www.cnblogs.com/dongying/p/4031382.html)

**一、Mybatis环境搭建及简单实例**

1\. 新建web项目， 添加依赖包：mybatis包、数据库驱动包(我使用的是mysql)、日志包(我使用的是log4j)， 由于我的是maven项目， 那么添加依赖包就简单了，直接在pom.xml添加依赖即可。

pom.xml:

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
<dependencies>
      <!-- 添加junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <!-- 添加log4j -->
    <dependency>
        <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    
    <!-- 添加mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
        <version>3.2.6</version>
    </dependency>
    
    <!-- 添加mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.12</version>
    </dependency>
    
  </dependencies>
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

2\. 配置log4j, 配置mybatis

　　在classpath建立一个用于配置log4j的配置文件log4j.properties, 再建立一个用于配置Mybatis的配置文件configuration.xml（文件可随便命名）。log4j的配置，我就不多说，这儿主要说一下configuration.xml:

configuration.xml:

3\. 开始写Demo

　　首先，在mysql数据库test1建立一张表user:

　　![](http://images.cnitblog.com/blog/677727/201410/171555515604364.png)

　　然后，开始编写java代码。

　　看看我的项目结构：

　　![](http://images.cnitblog.com/blog/677727/201410/171541059984310.png)

 

先编写一个实体类User: User类用于与User表相对应。

User:

再编写一个UserDao 接口：

UserDao:

再编写一个userDao-mapping.xml （可随便命名）:

userDao-mapping.xml:

userDao-mapping.xml相当于是UserDao的实现， 同时也将User实体类与数据表User成功关联起来。

4\. 下面编写junit测试代码UserDaoTest：

　UserDaoTest:

　

好啦，这样一个简单的mybatis 的demo就能成功运行啦。通过这个demo, 应该你就也能初步看出mybatis的运行机制，如果不清楚，也没关系。从下一篇文章开始，才开始正式讲解mybatis。