Firstly, give you a simple example as a tutorial, then you will get an another example to explain the detail usage:
In this examples you will see how to create or define a data mapper using the MyBatis. The mapper will communicate our application with the underlying databases where the data is stored. MyBatis data mapper is defined as an interface
object.
We can either use annotations or the xml mapper to define our database query.
In the first steps we will create a domain object, a simple pojo to store our data in the object world. The attributes / fields of our pojo resemble the structure of our records
table
in the database.
package org.kodejava.example.mybatis.domain;
import java.io.Serializable;
import java.util.Date;
public class Record implements Serializable {
private Integer id;
private String title;
private Date releaseDate;
private Integer artistId;
private Integer labelId;
private Date created;
private Date modified;
public Record() {
}
//
// Define the getters and setters for our pojo.
//
// ...
// ...
// ...
@Override
public String toString() {
return "Record{" +
"id=" + id +
", title='" + title + "'" +
", releaseDate=" + releaseDate +
", artistId=" + artistId +
", labelId=" + labelId +
"}";
}
}
Next we define the mapper interface
code, we’ll create a RecordMapper.java
file
that contains a method to get data from the table. At this time the interface
will be as the following:
package org.kodejava.example.mybatis.persistence;
import org.kodejava.example.mybatis.domain.Record;
public interface RecordMapper {
/**
* Get a single Record from the database based on the record
* identified.
*
* @param id record identifier.
* @return a record object.
*/
Record getRecord(int id);
}
After create the ResultMapper.java
interface we create a RecordMapper.xml
file
that defines the queries used by our mapper. Here is how it looks like:
<?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="org.kodejava.example.mybatis.persistence.RecordMapper">
<resultMap id="recordResultMap" type="record">
<result column="release_date" property="releaseDate"/>
<result column="artist_id" property="artistId"/>
<result column="label_id" property="labelId"/>
</resultMap>
<select id="getRecord" parameterType="int" resultMap="recordResultMap">
SELECT
id,
title,
release_date,
artist_id,
label_id,
created,
modified
FROM records
WHERE id = #{id}
</select>
</mapper>
To tell MyBatis about our mapper we need to define the mapper inside MyBatis configuration file. We register the mapper inside the <mappers>
element
of the configuration file.
<?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="record" type="org.kodejava.example.mybatis.domain.Record"/>
</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/mediadb"/>
<property name="username" value="root"/>
<property name="password" value="welcome"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/kodejava/example/mybatis/persistence/RecordMapper.xml"/>
</mappers>
</configuration>
Finally, we create a simple application to use the data mapper to get record data from the database.
package org.kodejava.example.mybatis;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.kodejava.example.mybatis.domain.Record;
import org.kodejava.example.mybatis.persistence.RecordMapper;
import java.io.Reader;
public class MediaClient {
public static void main(String[] args) throws Exception {
String resource = "org/kodejava/example/mybatis/Configuration.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(reader);
SqlSession session = factory.openSession();
try {
RecordMapper mapper = session.getMapper(RecordMapper.class);
Record record = mapper.getRecord(1);
System.out.println("Record = " + record);
} finally {
session.close();
}
}
}
在SSH框架盛行的时代,ORM和持久层框架都不断响彻在耳边,今天小编就带领大家一起来认识另一种持久层框架;
一、基本概况
MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO对象映射成数据库中的记录。
框架图如下;

二、入门教程(使用mysql的数据库)
1. 搭建开发环境:
♔ 创建一个普通的Java项目,如下图所示:

♔
添加数据库和mybatis的jar包;

♔创建数据库,并建立数据表:
-
<span style="font-size:18px;">CREATE TABLE `items` (
-
`id` int(11) NOT NULL AUTO_INCREMENT,
-
`name` varchar(32) NOT NULL COMMENT '商品名称',
-
`price` float(10,1) NOT NULL COMMENT '商品定价',
-
`detail` text COMMENT '商品描述',
-
`pic` varchar(64) DEFAULT NULL COMMENT '商品图片',
-
`createtime` datetime NOT NULL COMMENT '生产日期',
-
PRIMARY KEY (`id`)
-
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-
-
/*Table structure for table `orderdetail` */
-
-
CREATE TABLE `orderdetail` (
-
`id` int(11) NOT NULL AUTO_INCREMENT,
-
`orders_id` int(11) NOT NULL COMMENT '订单id',
-
`items_id` int(11) NOT NULL COMMENT '商品id',
-
`items_num` int(11) DEFAULT NULL COMMENT '商品购买数量',
-
PRIMARY KEY (`id`),
-
KEY `FK_orderdetail_1` (`orders_id`),
-
KEY `FK_orderdetail_2` (`items_id`),
-
CONSTRAINT `FK_orderdetail_1` FOREIGN KEY (`orders_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
-
CONSTRAINT `FK_orderdetail_2` FOREIGN KEY (`items_id`) REFERENCES `items` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
-
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-
-
/*Table structure for table `orders` */
-
-
CREATE TABLE `orders` (
-
`id` int(11) NOT NULL AUTO_INCREMENT,
-
`user_id` int(11) NOT NULL COMMENT '下单用户id',
-
`number` varchar(32) NOT NULL COMMENT '订单号',
-
`createtime` datetime NOT NULL COMMENT '创建订单时间',
-
`note` varchar(100) DEFAULT NULL COMMENT '备注',
-
PRIMARY KEY (`id`),
-
KEY `FK_orders_1` (`user_id`),
-
CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
-
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-
-
/*Table structure for table `user` */
-
-
CREATE TABLE `user` (
-
`id` int(11) NOT NULL AUTO_INCREMENT,
-
`username` varchar(32) NOT NULL COMMENT '用户名称',
-
`birthday` date DEFAULT NULL COMMENT '生日',
-
`sex` char(1) DEFAULT NULL COMMENT '性别',
-
`address` varchar(256) DEFAULT NULL COMMENT '地址',
-
PRIMARY KEY (`id`)
-
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;</span>
2. 实例-- 查询用户表中姓名为“小明”的模糊查询
✎
在src中建立数据库的配置文件(db.properties)和日志的配置文件(log4j.properties),并创建用户的实体类(User.java)
db.properties
-
<span style="font-size:18px;">jdbc.driver=com.mysql.jdbc.Driver
-
jdbc.url=jdbc:mysql://localhost:3306/mybatis
-
jdbc.username=root
-
jdbc.password=mysql</span>
log4j.properties:
-
<span style="font-size:18px;"># Global logging configuration
-
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
-
log4j.rootLogger=DEBUG, stdout
-
# Console output...
-
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
-
</span>
User.java:
-
<span style="font-size:18px;">package cn.itcast.mybatis.po;
-
-
import java.util.Date;
-
-
public class User {
-
-
//属性名和数据库表的字段对应
-
private int id;
-
private String username;// 用户姓名
-
private String sex;// 性别
-
private Date birthday;// 生日
-
private String address;// 地址
-
public int getId() {
-
return id;
-
}
-
public void setId(int id) {
-
this.id = id;
-
}
-
public String getUsername() {
-
return username;
-
}
-
public void setUsername(String username) {
-
this.username = username;
-
}
-
public String getSex() {
-
return sex;
-
}
-
public void setSex(String sex) {
-
this.sex = sex;
-
}
-
public Date getBirthday() {
-
return birthday;
-
}
-
public void setBirthday(Date birthday) {
-
this.birthday = birthday;
-
}
-
public String getAddress() {
-
return address;
-
}
-
public void setAddress(String address) {
-
this.address = address;
-
}
-
@Override
-
public String toString() {
-
return "User [id=" + id + ", username=" + username + ", sex=" + sex
-
+ ", birthday=" + birthday + ", address=" + address + "]";
-
}
-
-
-
}</span>
✎
然后建立系统的映射文件sqlMapConfig.xml(用来加载映射文件Mapper):
-
<span style="font-size:18px;"><?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>
-
-
<!-- 加载属性文件 -->
-
<properties resource="db.properties">
-
<!--properties中还可以配置一些属性名和属性值 -->
-
<!-- <property name="jdbc.driver" value=""/> -->
-
</properties>
-
<!-- 全局配置参数,需要时再设置 -->
-
<!-- <settings>
-
-
</settings> -->
-
-
<!-- 别名定义 -->
-
<typeAliases>
-
-
<!-- 针对单个别名定义
-
type:类型的路径
-
alias:别名
-
-->
-
<!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> -->
-
<!-- 批量别名定义
-
指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
-
-->
-
<package name="cn.itcast.mybatis.po"/>
-
-
</typeAliases>
-
-
<!-- 和spring整合后 environments配置将废除-->
-
<environments default="development">
-
<environment id="development">
-
<!-- 使用jdbc事务管理,事务控制由mybatis-->
-
<transactionManager type="JDBC" />
-
<!-- 数据库连接池,由mybatis管理-->
-
<dataSource type="POOLED">
-
<property name="driver" value="${jdbc.driver}" />
-
<property name="url" value="${jdbc.url}" />
-
<property name="username" value="${jdbc.username}" />
-
<property name="password" value="${jdbc.password}" />
-
</dataSource>
-
</environment>
-
</environments>
-
<!-- 加载 映射文件 -->
-
<mappers>
-
<mapper resource="sqlmap/User.xml"/>
-
-
<!--通过resource方法一次加载一个映射文件 -->
-
<!-- <mapper resource="mapper/UserMapper.xml"/> -->
-
-
<!-- 通过mapper接口加载单个 映射文件
-
遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
-
上边规范的前提是:使用的是mapper代理方法
-
-->
-
<!-- <mapper class="cn.itcast.mybatis.mapper.UserMapper"/> -->
-
-
<!-- 批量加载mapper
-
指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
-
遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
-
上边规范的前提是:使用的是mapper代理方法
-
-->
-
<package name="cn.itcast.mybatis.mapper"/>
-
-
</mappers>
-
-
</configuration>
-
</span>
✎ 在上述文件的路径“cn.itcast.mybatis.mapper”下建立用户的实体文件(UserMapper.java)和实体映射文件(UserMapper.xml);
UserMapper.java(主要是mapper的代理接口)
-
<span style="font-size:18px;">package cn.itcast.mybatis.mapper;
-
-
import java.util.List;
-
-
import cn.itcast.mybatis.po.User;
-
import cn.itcast.mybatis.po.UserCustom;
-
import cn.itcast.mybatis.po.UserQueryVo;
-
-
public interface UserMapper {
-
-
//根据用户名列模糊查询用户列表
-
public List<User> findUserByName(String name)throws Exception;
-
-
}
-
</span>
UserMapper的实体映射文件(编辑程序功能用到的sql语句)
-
<span style="font-size:18px;"><?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">
-
-
<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
-
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-
-->
-
<mapper namespace="test">
-
-
<!-- 根据用户名称模糊查询用户信息,可能返回多条
-
resultType:指定就是单条记录所映射的java对象 类型
-
${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
-
使用${}拼接sql,引起 sql注入
-
${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
-
-->
-
<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
-
SELECT * FROM USER WHERE username LIKE '%${value}%'
-
</select>
-
-
</mapper>
-
</span>
PS:【与hibernate框架中的层结构一样都需要dao和daoImpl,这里dao和daoImpl就不再赘述】:
✎上述的准备工作都准备完毕之后,我们建立一个单元测试代码如下;
-
<span style="font-size:18px;">package cn.itcast.mybatis.first;
-
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.util.Date;
-
import java.util.List;
-
-
import org.apache.ibatis.io.Resources;
-
import org.apache.ibatis.session.SqlSession;
-
import org.apache.ibatis.session.SqlSessionFactory;
-
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
-
import org.junit.Test;
-
-
import cn.itcast.mybatis.po.User;
-
-
public class MybatisFirst {
-
-
// 根据用户名称模糊查询用户列表
-
@Test
-
public void findUserByNameTest() throws IOException {
-
// mybatis配置文件
-
String resource = "SqlMapConfig.xml";
-
// 得到配置文件流
-
InputStream inputStream = Resources.getResourceAsStream(resource);
-
-
// 创建会话工厂,传入mybatis的配置文件信息
-
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
-
.build(inputStream);
-
-
// 通过工厂得到SqlSession
-
SqlSession sqlSession = sqlSessionFactory.openSession();
-
// list中的user和映射文件中resultType所指定的类型一致
-
List<User> list = sqlSession.selectOne("test.findUserByName", "小明");
-
System.out.println(list);
-
sqlSession.close();
-
-
}
-
}
-
</span>
到这里,使用mybatis+ mysql 实现模糊查询的功能就实现了,有兴趣的可以动手尝试一下;
三、总结
mybatis是Apache下的顶级项目,是一个持久层框架,是一个不完全的ORM框架;
mybatis使得程序将主要精力放在了sql上,它通过自身提供的映射方式,自由且灵活地生成满足程序需要的sql语句(半自动化,大部分需要程序员自己编写);
mybatis可以将向PreparedStatement中输入的参数自动进行输入映射,将查询结果集灵活映射成Java对象(输出映射);