Mybatis简单介绍
MyBatis是Java ORM 框架,类比于:Hibernate ORM,与Hibernate相比其性能会更好些,但是比JDBC稍微差一些。这里不做过多介绍。本文通过示例来阐述Mybatis入门。
HelloWord (入门)
1. 环境准备
开发工具:IDEA
数据库:MySQL
语言:Java + Mybatis
1.1 包引入(pom.xml)
maven仓库:http://mvnrepository.com/
引入:Mybatis、Junit、Mysql驱动包
<?xml version="1.0" encoding="UTF-8"?>
<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>csdn</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<!-- or whatever version you use -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.2 配置文件(mybatis-config.xml)
Mybatis需要配置一个全局配置文件,用于管理连接、mapper等信息,一般命名为:mybatis-config.xml存放在类路径的根目录下。
jdbc.properties
# 驱动名称使用的高版本
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/csdn?charset=utf8
db.username=root
db.password=root
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>
<!-- 加载properties配置,也可以设置 -->
<properties resource="jdbc.properties">
</properties>
<!-- 开启debug模式,方便查看sql情况 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 环境配置(开发环境、测试环境、预发布环境等多套环境DB配置) -->
<environments default="test">
<!-- 每个环境对应一个environment配置 -->
<environment id="test">
<!-- 事务管理类型
JDBC: 使用Jdbc的事务管理机制
MANAGED: 容器管理,详情参考:http://www.mybatis.org/mybatis-3/zh/configuration.html#environments
-->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据源:连接池方式
UNPOOLED: 非连接池
POOLED: 连接池
JNDI: 容器管理
-->
<dataSource type="POOLED">
<property name="driver" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<!-- 还可以做一些连接池的配置,这里不做展开 -->
</dataSource>
</environment>
</environments>
<mappers>
<!-- 命名需要"实体类名.xml"-->
<mapper resource="mapper/User.xml"/>
</mappers>
</configuration>
1.3 表结构
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '' COMMENT '用户名',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=210 DEFAULT CHARSET=utf8 COMMENT='用户表'
2. 实体(POJO)
package com.mybatis.helloword.pojo;
import java.io.Serializable;
import java.util.Date;
/**
* Created by wangzhiping on 17/2/21.
*/
public class User implements Serializable{
private int id;
private String name;
private Date createdAt;
private Date updatedAt;
public User() {
}
public User(int id, String name, Date createdAt, Date updatedAt) {
this.id = id;
this.name = name;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
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 Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", createdAt=" + createdAt +
", updatedAt=" + updatedAt +
'}';
}
}
3. 实体映射配置
ORM最大的核心在于屏蔽底层DB操作细节,将table和实体类进行映射关联到一起。在mybatis中,是通过Mapper文件来做好映射的。
<?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:最佳实践是设置为该实体类的全包名 -->
<mapper namespace="com.mybatis.helloworld.pojo.User">
<!-- resultMap -->
<resultMap id="UserType" type="com.mybatis.helloworld.pojo.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 特别注意这里
在User实体类中我们使用的命名是驼峰形式,默认mybatis是user属性名与db字段名一致。如果不一致,需要
做好映射关系,以免出现注入结果为null
-->
<result property="createdAt" column="created_at" />
<result property="updatedAt" column="updated_at" />
</resultMap>
<!-- select标签:制定查询操作 -->
<select id="findById" parameterType="int" resultMap="UserType">
SELECT * FROM user WHERE id=#{id}
</select>
<!-- insert标签:插入操作 -->
<insert id="add" parameterType="com.mybatis.helloworld.pojo.User">
INSERT INTO user
VALUES(null, #{name}, #{createdAt}, #{updatedAt})
</insert>
<!-- update标签: 更新操作 -->
<update id="update" parameterType="com.mybatis.helloworld.pojo.User" >
UPDATE user
SET name=#{name}, created_at=#{createdAt}, updated_at=#{updatedAt}
WHERE id=#{id}
</update>
<!-- delete标签:删除操作 -->
<delete id="deleteById" parameterType="int">
DELETE FROM user
WHERE id=#{id}
</delete>
<!-- noice:
1、每个标签都有一个id,是唯一标识一个操作的sqlID;
2、标签分为select, insert, update, delete对应crud操作;
这个文件必须添加到mybatis-config.xm文件中,不然根本不知道实体类如何与db进行映射
-->
</mapper>
2. 代码实现
准备好了各种配置文件和映射关系,接下来如何实现基本的CRUD操作呢?Mybatis有几个核心类:
1、SqlSessionFactory:SqlSession工厂,重量级对象,创建和销毁代价很大,而且全局一个即可。
2、SqlSession:线程不安全,对应每次的连接操作对象;拿到它就可以对db干活了
MybatisUtils.java
package com.mybatis.helloworld.dao;
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 java.io.IOException;
/**
* Created by wangzhiping on 17/2/21.
*/
public class MybatisUtils {
private static MybatisUtils mybatisUtils = null;
private SqlSessionFactory factory = null;
private MybatisUtils(){
init();
}
public static MybatisUtils getInstance(){
if (mybatisUtils == null) {
mybatisUtils = new MybatisUtils();
}
return mybatisUtils;
}
private void init() {
try {
factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取session
*/
public SqlSession getSession() {
return factory.openSession();
}
/**
* 关闭session
*/
public void closeSession(SqlSession session) {
if (session != null) {
session.close();
}
}
}
Unit Test
package com.mybatis.helloworld.test;
import com.mybatis.helloworld.pojo.User;
import com.mybatis.helloworld.dao.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.Date;
/**
* Created by wangzhiping on 17/2/21.
*/
public class UserTest {
@Test
public void testAdd(){
SqlSession session = MybatisUtils.getInstance().getSession();
try{
session.insert(User.class.getName() + ".add", new User(null, "wangzhiping", new Date(), new Date()));
session.commit();
}catch (Exception e) {
session.rollback();
e.printStackTrace();
} finally {
MybatisUtils.getInstance().closeSession(session);
}
}
@Test
public void testFindById(){
SqlSession session = MybatisUtils.getInstance().getSession();
try{
User user = session.selectOne(User.class.getName() + ".findById", 210);
System.out.println(user);
}catch (Exception e) {
session.rollback();
e.printStackTrace();
} finally {
MybatisUtils.getInstance().closeSession(session);
}
}
@Test
public void testDeleteById(){
SqlSession session = MybatisUtils.getInstance().getSession();
try{
session.delete(User.class.getName() + ".deleteById", 210);
session.commit();
}catch (Exception e) {
session.rollback();
e.printStackTrace();
} finally {
MybatisUtils.getInstance().closeSession(session);
}
}
@Test
public void testUpdate(){
SqlSession session = MybatisUtils.getInstance().getSession();
try{
session.update(User.class.getName() + ".update", new User(201, "wangzhiping", new Date(), new Date()));
session.commit();
}catch (Exception e) {
session.rollback();
e.printStackTrace();
} finally {
MybatisUtils.getInstance().closeSession(session);
}
}
}
项目地址
github: https://github.com/wzpthq/csdn_mybatis.git 会陆续更新mybatis相关的用法和处理
本文重点在于先感受一下,之后会抽丝剥茧来描述mybatis框架的内容。