Mybatis基础入门 I
作为ORM的重要框架,MyBatis是iBatis的升级版。Mybatis完全将SQL语句交给编程人员掌控,这点和Hibernate的设计理念不同(至于Hibernate的理念,待我先学习学习)。
下面的教程,是一个基于STS(也可以是eclipse,需要事先安装好maven)的一个入门级教程。下文分为两个部分,第一部门为简单版教程,第二部分是step-by-step教程。
Part one
简单教程:
- 新建maven工程。
- 添加mybatis和mysql包,以及log4j的包。
- 新建或者使用现存的数据库,并准备好若干语句。例如使用mysql的默认数据库world。
- 新建mybatis-config.xml配置文件,作为mybaits的基础配置。
- 新建POJO,City。
- 新建mapper文件:city.xml,进行配置。
- 新建Interface,CityMapper,对应city.xml的方法。
- 新建Class: CityService,并implemente CityMapper,实现各种方法。
- 新建Class:MyBatisSqlSessionFactory,用户获取mybatis的session
- 新建测试文件,进行测试。
--完--
Part two
这部分对第一部分进行细化,并配以图片说明:
详细教程:
- 新建maven工程。
- 选择新建工程,选择maven项目
- 选择quickStart类型的maven:

- 输入Group Id和Artifact Id并完成工程:

- 添加mybatis和mysql包,以及log4j的包。
- 编辑pom.xml文件,添加以下包:

其中红框内的为必选,其余随意。
其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>
整个工程的目录如下:

- 新建或者使用现存的数据库,并准备好若干语句。例如使用mysql的默认数据库world。
这是个现成的数据库(懒得新建一个),本教程只用到其中的一张表,表结构如下:
- 新建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>逐一解释:

- 新建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;
} } - 新建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>解释如下:

- 新建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();
} - 新建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();
}
}
} - 新建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 } } - 新建测试文件,进行测试。
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());
}
}
} - 输出结果:

文章以贴代码为主。工程下载地址:https://www.dropbox.com/s/w3j5jhy3lc12hzt/mybatisdemo.zip,请继续关注。
后续将整合spring,使用mybatis-generator来生成绝大多数的代码。
Mybatis基础入门 I的更多相关文章
- MyBatis基础入门《二十》动态SQL(foreach)
MyBatis基础入门<二十>动态SQL(foreach) 1. 迭代一个集合,通常用于in条件 2. 属性 > item > index > collection : ...
- MyBatis基础入门《十九》动态SQL(set,trim)
MyBatis基础入门<十九>动态SQL(set,trim) 描述: 1. 问题 : 更新用户表数据时,若某个参数为null时,会导致更新错误 2. 分析: 正确结果: 若某个参数为nul ...
- MyBatis基础入门《十八》动态SQL(if-where)
MyBatis基础入门<十八>动态SQL(if-where) 描述: 代码是在<MyBatis基础入门<十七>动态SQL>基础上进行改造的,不再贴所有代码,仅贴改动 ...
- MyBatis基础入门《十七》动态SQL
MyBatis基础入门<十七>动态SQL 描述: >> 完成多条件查询等逻辑实现 >> 用于实现动态SQL的元素主要有: > if > trim > ...
- MyBatis基础入门《十六》缓存
MyBatis基础入门<十六>缓存 >> 一级缓存 >> 二级缓存 >> MyBatis的全局cache配置 >> 在Mapper XML文 ...
- MyBatis基础入门《十五》ResultMap子元素(collection)
MyBatis基础入门<十五>ResultMap子元素(collection) 描述: 见<MyBatis基础入门<十四>ResultMap子元素(association ...
- MyBatis基础入门《十四》ResultMap子元素(association )
MyBatis基础入门<十四>ResultMap子元素(association ) 1. id: >> 一般对应数据库中改行的主键ID,设置此项可以提高Mybatis的性能 2 ...
- MyBatis基础入门《十三》批量新增数据
MyBatis基础入门<十三>批量新增数据 批量新增数据方式1:(数据小于一万) xml文件 接口: 测试方法: 测试结果: =============================== ...
- MyBatis基础入门《十二》删除数据 - @Param参数
MyBatis基础入门<十二>删除数据 - @Param参数 描述: 删除数据,这里使用了@Param这个注解,其实在代码中,不使用这个注解也可以的.只是为了学习这个@Param注解,为此 ...
- MyBatis基础入门《十 一》修改数据
MyBatis基础入门<十 一>修改数据 实体类: 接口类: xml文件: 测试类: 测试结果: 数据库: 如有问题,欢迎纠正!!! 如有转载,请标明源处:https://www.cnbl ...
随机推荐
- 向Oracle数据库中CLOB插入数据报错问题
今天在项目中向数据库的CLOB属性插入一段篇文章(1000~2000)字就会报一个字符串过长的错误. 网上说用流来处理,没有这么做.这像是一个Bug,只要把插入的数据,默认扩充到2000以上就ok了. ...
- js 数组排除重复值(string)
前提:数组中的元素类型为:string 在网上看了许多高大尚的文章,还是解决不了我的string arry 的问题,只能怪自己脑残了,上代码: <!DOCTYPE html> <ht ...
- ip聚合(百度之星资格赛1003)
IP聚合 点击这里 Problem Description 当今世界,网络已经无处不在了,小度熊由于犯了错误,当上了度度公司的网络管理员,他手上有大量的 IP列表,小度熊想知道在某个固定的子网掩码下, ...
- UVA 816 Abbott’s Revenge
bfs求最短路,递归打印最短路的具体路径: 难点: 当前状态和转弯方式很复杂,要仔细处理: 递归打印:用一个数组存储路径中结点的前一个节点,递归查找 (bfs无法确定下一个结点,但对于没一个结点,它的 ...
- 解析XML【C#】
1.XML元素XML元素包含一个开标记.元素中的数据.闭标记例如:<book>book name</book>其中book是元素名称 book name是元素数据元素名称区 ...
- 什麼是 N-key 與按鍵衝突?原理說明、改善技術、選購注意完全解析
不管是文書處理或遊戲中,我們都經常會使用到組合鍵,也就是多顆按鍵一起按下,執行某些特定的功能.有時候你可能會發現,明明只按下2顆鍵,再按下第3顆鍵時訊號卻沒有輸出.要是打報告到一半遇到這種狀況還好,如 ...
- 1.elk 入门示例
zjtest7-frontend:/usr/local/logstash-2.3.4/bin# ./logstash -e 'input{stdin{}} output{stdout{codec=&g ...
- 【HDU 4451 Dressing】水题,组合数
有衣服.裤子.鞋数量分别为n,m,k,给出p对不和谐的衣-裤或裤-鞋搭配,问一共有多少种和谐的衣裤鞋的搭配. 全部的组合有Cn1Cm1Ck1种. 设p对中有p1对衣-裤,p2对裤-鞋,则不和谐的搭配共 ...
- 【LeetCode练习题】Scramble String
Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two no ...
- linux 启动 oracle数据库
第一步:切换到oracle用户 su - oracle 第二步:启动oracle数据库监听 lsnrctl start 第三步:输入下方命令,出现:sql> sqlplus /nolog 第四步 ...