作为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. kettle查询出来的真实值被识别为null

    问题描述: 通过关联表查询出来的applyId(申请编号),在数据流里也是能看到的,但是在写入到数据表中的时候,由于设置了这个字段不能为空,所以一直报错. 问题实质: 数据流内存在的数据却不能保存,原 ...

  2. UTF-8、GB2312都支持的汉字截取函数

    <?php/*Utf-8.gb2312都支持的汉字截取函数cut_str(字符串, 截取长度, 开始长度, 编码);编码默认为 utf-8开始长度默认为 0*/ function cut_str ...

  3. table中td,th不能设置margin

    首先,我们需要知道的是:我们可以对表格table设置margin,而不能设置padding;对单元格td设置padding,而不能设置margin.所以说,我们不能对单元格td设置margin属性来调 ...

  4. php number_format()保留小数点后几位有效数的函数 千位分组来格式化数字(转)

    PHP保留小数点后2位的函数number_format number_format(带小数点的书,小数点后保留的位数) number_format(8.3486,2);  //取得小数点后2位有效数/ ...

  5. codeforces 518A. Vitaly and Strings

    A. Vitaly and Strings time limit per test 1 second memory limit per test 256 megabytes input standar ...

  6. ca 证书、签名

    1.我现在没有个人CA证书,使用.中信建投网上交易,是如何保障安全的呢? 如果您目前没有个人CA证书,使用.中信建投网上交易,系统其实也是用CA证书的RSA体系进行加密的. 您在输入账户和密码进行登录 ...

  7. 快速配置 Samba 将 Linux 目录映射为 Windows 驱动器

    原文链接 samba client ubuntu redhat ubuntu gui tools 1,列出某个IP地址所提供的共享文件夹 smbclient -L 198.168.0.1   2,在s ...

  8. 使用Node.js快速搭建WebSocket server

    原文地址:http://my.oschina.net/yushulx/blog/309413 目录[-] 安装 服务端 客户端 参考 安装 ? 1 npm install ws 服务端 server. ...

  9. [Linux]shell编程基础/linux基础入门

    声明执行程序 #!/bin/bash 用来告诉系统使用/bin/bash 程序来执行该脚本.譬如python 脚本,可以这样写: #!/usr/bin/python   赋值和引用 赋值公式: 变量名 ...

  10. ALLEN-XIE

    ALLEN-XIE ABOUT   Allen Xie是一家坚持理念至上的西装定制店.我们的价值观渗透于我们所做的每一件事中,从而确保始终遵循自己的风格.我们坚持用最高标准要求自己,因此,在制衣过程中 ...