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 ...
随机推荐
- Velocity中避免null引起的数据问题
请先看下面一段代码: #foreach($id in [1..50]) #set($user = $User.Get($id)) $id : ${user.name} #end 上面这段代码中,假设只 ...
- Putty使用公钥认证时,报错:Disconnected: No supported authentication methods available(server sent:public key) 问题的解决
Putty使用公钥认证时,按照常规方法设置,一直报错:Disconnected: No supported authentication methods available (server sent: ...
- 网络受限下,使用Nexus要解决的两个问题
在网络受限的情况下,使用nexus总会遇到这么两个问题,让你头疼. 我头疼过了,为了不让大家头疼,把解决方案放在这里,供大家参考. 问题一.背景: 由于网络原因,Nexus无法更新远程仓库的索引. ...
- ip聚合(百度之星资格赛1003)
IP聚合 点击这里 Problem Description 当今世界,网络已经无处不在了,小度熊由于犯了错误,当上了度度公司的网络管理员,他手上有大量的 IP列表,小度熊想知道在某个固定的子网掩码下, ...
- 五个典型的JavaScript面试题
问题1: 范围(Scope) 思考以下代码: 1 2 3 4 5 (function() { var a = b = 5; })(); console.log(b); 控制台(console ...
- 使用AES加密的帮助类
在开发中经常使用加密/解密对一些内容进行处理,比如密码在存入数据库之前先经过加密处理等等,这里就把一个加密帮助类代码贴出来,供以后查找使用. 这个帮助类主要功能是对字符串和字节数组进行加密解密处理. ...
- MEMS加速度计工作原理
一般加速度计有两块芯片组成,一块是MEMS传感器,另一块是客户化的信号处理芯片. 加速度计也称惯性传感器,因为它的工作原理就是靠MEMS中可移动部分的惯性.由于中间电容板的质量很大,而且它是一种悬臂构 ...
- 键盘有没有NKRO ?微软帮你测
玩家甚至媒体的解读是错的,所以小编在此重点说明一些概念.并分享如何测试.在许多游戏与软体中都会使用组合键功能,也就是同时按下特定几个按键之后就能触发特别的功能,简单的说就是一些动作的快捷键.不过,有时 ...
- GO的GDB调试
GoLang语言,学了很久,一直觉得它单步调试有较多问题,最近才知道自已对它了解得太少了.原来GO语言对GDB的版本是至少为gdb7以上,才能比较好的打印任意变量,如果低于这个版本,则才会出一些问题. ...
- [Linux]shell编程基础/linux基础入门
声明执行程序 #!/bin/bash 用来告诉系统使用/bin/bash 程序来执行该脚本.譬如python 脚本,可以这样写: #!/usr/bin/python 赋值和引用 赋值公式: 变量名 ...