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 ...
随机推荐
- Linux下,命令 wget 的使用
wget是一个从网络上自动下载文件的自由工具.它支持HTTP,HTTPS和FTP协议,可以使用HTTP代理. 所谓的自动下载是指,wget可以在用户退出系统的之后在后台执行.这意味这你可以登录系统, ...
- MySQL数据库主从同步安装与配置总结
MySQL的主从同步是一个很成熟的架构,优点为: ①在从服务器可以执行查询工作(即我们常说的读功能),降低主服务器压力: ②在从主服务器进行备份,避免备份期间影响主服务器服务: ③当主服务器出现问题时 ...
- 使用jsp生成验证码
在开发中验证码是比较常用到有效防止这种问题对某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试的方式. 此演示程序包括三个文件: 1.index.jsp:登录页面 2.image.jsp:生成 ...
- QTDesigner的QVBoxLayout自动随窗口拉伸
在MainWindow的构造函数中添加如下代码://设置Uiui.setupUi(this); //使Ui可自适应父窗口大小QVBoxLayout* mainLayout = new QVBoxLay ...
- Inno Setup技巧[界面]自定义安装向导小图片宽度
原文 blog.sina.com.cn/s/blog_5e3cc2f30100cj7e.html 英文版中安装向导右上角小图片的大小为55×55,汉化版中为55×51.如果图片超过规定的宽度将会被压 ...
- zookeeper数据弱一致性
zookeeper本身支持单机部署和集群部署,生产环境建议使用集群部署,因为集群部署不存在单点故障问题,并且zookeeper建议部署的节点个数为奇数个,只有超过一半的机器不可用整个zk集群才不可用. ...
- 获取ActiveX控件本身所在的路径 和 error PRJ0050
一. CString GetCurPath() { TCHAR exeFullPath[MAX_PATH]; CString strPath; ...
- sed简单实例练习
sedfile内容如下: Steve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300 Betty Boop: ...
- C++中的动态类型与动态绑定、虚函数、运行时多态的实现
动态类型与静态类型 静态类型 是指不需要考虑表达式的执行期语义,仅分析程序文本而决定的表达式类型.静态类型仅依赖于包含表达式的程序文本的形式,而在程序运行时不会改变.通俗的讲,就是上下文无关,在编译时 ...
- Android九宫格图片(9.png)的讲解与制作
刚开始学习Android的时候,会见到res/drawable的几个文件里面有*.9.png格式命名的图片文件.起初以为这只是Android素材的一些特殊命名,其实不是.它是能实现图片素材拉伸.收缩不 ...