作为ORM的重要框架,MyBatis是iBatis的升级版。Mybatis完全将SQL语句交给编程人员掌控,这点和Hibernate的设计理念不同(至于Hibernate的理念,待我先学习学习)。

下面的教程,是一个基于STS(也可以是eclipse,需要事先安装好maven)的一个入门级教程。下文分为两个部分,第一部门为简单版教程,第二部分是step-by-step教程。

Part one

简单教程:

  1. 新建maven工程。
  2. 添加mybatis和mysql包,以及log4j的包。
  3. 新建或者使用现存的数据库,并准备好若干语句。例如使用mysql的默认数据库world。
  4. 新建mybatis-config.xml配置文件,作为mybaits的基础配置。
  5. 新建POJO,City。
  6. 新建mapper文件:city.xml,进行配置。
  7. 新建Interface,CityMapper,对应city.xml的方法。
  8. 新建Class: CityService,并implemente CityMapper,实现各种方法。
  9. 新建Class:MyBatisSqlSessionFactory,用户获取mybatis的session
  10. 新建测试文件,进行测试。

--完--

Part two

这部分对第一部分进行细化,并配以图片说明:

详细教程:

  1. 新建maven工程。
    • 选择新建工程,选择maven项目
    • 选择quickStart类型的maven:
    • 输入Group Id和Artifact Id并完成工程:
  2. 添加mybatis和mysql包,以及log4j的包。
    • 编辑pom.xml文件,添加以下包:

      其中红框内的为必选,其余随意。

    其pom.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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>jacob</groupId>
<artifactId>mybatisdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>mybatisdemo</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>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>

      

    •   整个工程的目录如下:

  1.   新建或者使用现存的数据库,并准备好若干语句。例如使用mysql的默认数据库world。
    这是个现成的数据库(懒得新建一个),本教程只用到其中的一张表,表结构如下:

  2. 新建mybatis-config.xml配置文件,作为mybaits的基础配置。
    • 在src/main/resources中新建文件: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>
      <typeAliases>
      <typeAlias alias="City" type="jacob.domain.City" />
      </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://localhost:3306/world" />
      <property name="username" value="root" />
      <property name="password" value="111111" />
      </dataSource>
      </environment>
      </environments> <mappers>
      <mapper resource="jacob/mapper/city.xml" />
      </mappers>
      </configuration>
    • 逐一解释:

  3. 新建POJO,City。

    POJO的意思是:Plain Old Java Object,简单的说,就是一个普通的Java Bean。

    该Bean的内容对应于city表。

    文件如下:

     package jacob.domain;
    
     public class City {
    int id;
    String name;
    String countryCode;
    String district;
    int population; public int getId() {
    return id;
    } public void setId(int id) {
    this.id = id;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    } public String getCountryCode() {
    return countryCode;
    } public void setCountryCode(String countryCode) {
    this.countryCode = countryCode;
    } public String getDistrict() {
    return district;
    } public void setDistrict(String district) {
    this.district = district;
    } public int getPopulation() {
    return population;
    } public void setPopulation(int population) {
    this.population = population;
    } }
  4. 新建mapper文件:city.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">
    <mapper namespace="jacob.mapper.CityMapper">
    <resultMap type="City" id="CityResult">
    <id property="id" column="ID" />
    <result property="name" column="name" />
    <result property="countryCode" column="CountryCode" />
    <result property="district" column="District" />
    <result property="population" column="Population" />
    </resultMap>
    <select id="selectCity" parameterType="int" resultMap="CityResult">
    select *
    from city where id = #{id}
    </select> <select id="selectAll" resultType="City">
    select * from city;
    </select> </mapper>

    解释如下:

  5. 新建Interface,CityMapper,对应city.xml的方法。

    代码如下:

     package jacob.mapper;
    
     import java.util.List;
    
     import jacob.domain.City;
    
     public interface CityMapper {
    City selectCity(int id); List<City> selectAll();
    }
  6. 新建Class: CityService,并implemente CityMapper,实现各种方法。

    代码如下:

     package jacob.services;
    
     import java.util.List;
    
     import jacob.domain.City;
    import jacob.mapper.CityMapper;
    import jacob.mybatisdemo.MyBatisSqlSessionFactory; import org.apache.ibatis.session.SqlSession;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory; public class CityService implements CityMapper {
    private Logger logger = LoggerFactory.getLogger(getClass()); public City selectCity(int id) {
    SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); try {
    CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
    return cityMapper.selectCity(id);
    } finally {
    sqlSession.close();
    }
    } public List<City> selectAll() {
    SqlSession sqlSession = MyBatisSqlSessionFactory.openSession(); try {
    CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);
    return cityMapper.selectAll();
    } finally {
    sqlSession.close();
    }
    }
    }
  7. 新建Class:MyBatisSqlSessionFactory,用户获取mybatis的session
     package jacob.mybatisdemo;
    
     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; public class MyBatisSqlSessionFactory { private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory getSqlSessionFactory() {
    if (sqlSessionFactory == null) {
    InputStream inputStream;
    try {
    inputStream = Resources
    .getResourceAsStream("mybatis-config.xml");
    sqlSessionFactory = new SqlSessionFactoryBuilder()
    .build(inputStream);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return sqlSessionFactory;
    } public static SqlSession openSession(){
    return getSqlSessionFactory().openSession();
    } public static void main(String[] args) {
    // TODO Auto-generated method stub } }
  8. 新建测试文件,进行测试。

     package jacob.mybatisdemo;
    
     import java.util.List;
    
     import jacob.domain.City;
    import jacob.services.CityService; public class App {
    public static void main(String[] args) {
    CityService cityService = new CityService();
    City result = cityService.selectCity(2);
    System.out.println(result.getName()); List<City> list = cityService.selectAll();
    for (City c : list) {
    System.out.println(c.getName());
    }
    }
    }
  9. 输出结果:

文章以贴代码为主。工程下载地址:https://www.dropbox.com/s/w3j5jhy3lc12hzt/mybatisdemo.zip,请继续关注。

后续将整合spring,使用mybatis-generator来生成绝大多数的代码。

Mybatis基础入门 I的更多相关文章

  1. MyBatis基础入门《二十》动态SQL(foreach)

    MyBatis基础入门<二十>动态SQL(foreach) 1. 迭代一个集合,通常用于in条件 2. 属性 > item > index > collection : ...

  2. MyBatis基础入门《十九》动态SQL(set,trim)

    MyBatis基础入门<十九>动态SQL(set,trim) 描述: 1. 问题 : 更新用户表数据时,若某个参数为null时,会导致更新错误 2. 分析: 正确结果: 若某个参数为nul ...

  3. MyBatis基础入门《十八》动态SQL(if-where)

    MyBatis基础入门<十八>动态SQL(if-where) 描述: 代码是在<MyBatis基础入门<十七>动态SQL>基础上进行改造的,不再贴所有代码,仅贴改动 ...

  4. MyBatis基础入门《十七》动态SQL

    MyBatis基础入门<十七>动态SQL 描述: >> 完成多条件查询等逻辑实现 >> 用于实现动态SQL的元素主要有: > if > trim > ...

  5. MyBatis基础入门《十六》缓存

    MyBatis基础入门<十六>缓存 >> 一级缓存 >> 二级缓存 >> MyBatis的全局cache配置 >> 在Mapper XML文 ...

  6. MyBatis基础入门《十五》ResultMap子元素(collection)

    MyBatis基础入门<十五>ResultMap子元素(collection) 描述: 见<MyBatis基础入门<十四>ResultMap子元素(association ...

  7. MyBatis基础入门《十四》ResultMap子元素(association )

    MyBatis基础入门<十四>ResultMap子元素(association ) 1. id: >> 一般对应数据库中改行的主键ID,设置此项可以提高Mybatis的性能 2 ...

  8. MyBatis基础入门《十三》批量新增数据

    MyBatis基础入门<十三>批量新增数据 批量新增数据方式1:(数据小于一万) xml文件 接口: 测试方法: 测试结果: =============================== ...

  9. MyBatis基础入门《十二》删除数据 - @Param参数

    MyBatis基础入门<十二>删除数据 - @Param参数 描述: 删除数据,这里使用了@Param这个注解,其实在代码中,不使用这个注解也可以的.只是为了学习这个@Param注解,为此 ...

  10. MyBatis基础入门《十 一》修改数据

    MyBatis基础入门<十 一>修改数据 实体类: 接口类: xml文件: 测试类: 测试结果: 数据库: 如有问题,欢迎纠正!!! 如有转载,请标明源处:https://www.cnbl ...

随机推荐

  1. Java路径问题最终解决方案—可定位所有资源的相对路径寻址

    1.在Java项目中,应该通过绝对路径访问文件,以下为访问的常用方法: 第一种方法:类名.class.getResource("/").getPath()+文件名 第二种方法:Th ...

  2. 踩坑学php(1)

    前言: 为什么要学php 呢?作为一个前端,一直有着了解后台的好奇心:作为一个计算机毕业的,一直有着实践更多设计模式和数据库相关的东西:而php 非常流行,拥有非常多的资源,入门应该容易: 为什么叫& ...

  3. 安装windows7和ubuntu双系统后引导项设置

    win7系统,U盘安装ubuntu,在选择[安装启动引导器的设备]时,1.如果你选择的是/dev/sda,即整个硬盘,他会将启动引导器使用grub进行系统引导,而不再使用windows loader, ...

  4. jQuery工具函数下

    测试操作 1.判断是否为数组对象 $(function () { //判断是否为数组对象 var arr = [1,2,3,4]; alert($.isArray(arr));//true }); 2 ...

  5. 七夕节(hd1215)干嘛今天做这题T_T

    七夕节 Problem Description 七夕节那天,月老来到数字王国,他在城门上贴了一张告示,并且和数字王国的人们说:"你们想知道你们的另一半是谁吗?那就按照告示上的方法去找吧!&q ...

  6. UVa230 Borrowers (STL)

     Borrowers  I mean your borrowers of books - those mutilators of collections, spoilers of the symmet ...

  7. python 解释器内建函数001

    python解释器内建函数列表如下: 001.abs() 求绝对值 #!/usr/bin/python if __name__=="__main__": print(abs(-10 ...

  8. html类,id规范命名

    DIV+CSS的命名规则 SEO(搜索引擎优化)有很多工作要做,其中对代码的优化是一个很关键的步骤.为了更加符合SEO的规范,下面中部IT网将对目前流行的CSS+DIV的命名规则整理如下: 页头:he ...

  9. 甲骨文推动Java进军“物联网”

    该公司希望在嵌入式设备开发项目上Java可以取代C     随着周二宣布对嵌入式的Java版本进行升级,甲骨文希望扩展该平台到新一代连接设备,又名物联网.甲骨文还希望,Java可以在一些嵌入式开发项目 ...

  10. ROS Node/Topic/Message/Service的一些问题

    1.Node http://blog.exbot.net/archives/1412 (摘自老王说ros) node干的什么活?callback queue里的活.这个callback queue里的 ...