1. 概述
1.1 什么是Mybatis?
Mybatis 是一个优秀的持久层框架,是对JDBC操作数据库的过程进行了封装.
1.2 Mybatis 操作数据库的方式
- 可以通过xml文件的方式执行sql;
- 可以通过注解的方式执行SQL;
1.3 Mybatis 操作数据库的七大步骤?
- SQLSession 传递SQL骨架给MappedStatement
- 由MappedStatement 结合骨架和SQL参数映射成完整的SQL语句
- 将完整的SQL语句交给Executer
- 执行SQL语句
- 返回结果集给MappedStatement
- 封装结果集
- 将结果集返回给SQLSession
1.4 Mybatis 的开发优点
- 简化了JDBC代码
- 支持连接池,提高程序执行效率
- Mybatis 是将SQL配置在mapper文件中,修改SQL不需要重新编译
- 将返回结果ResultSet自动封装成java对象
2. Mybatis 操作数据库具体实现
- 项目结构
2.1 创建一个数据库表
create database mytest;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '匿名',
`age` int(11) NOT NULL,
`sex` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '男',
`address` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
`email` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `email`(`email`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '匿名', 11, '男', '1111', '11111');
2.2 创建一个maven项目,配置pom.xml文件,导入相关依赖
<?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>com.it</groupId>
<artifactId>mybatis_lean</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- 连接mysql数据库驱动,这里是8.0以上版本-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>
</project>
2.3 创建mybatis 核心配置文件
jdbc.properties文件,描述连接数据库的属性
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mytest
jdbc.username = root
jdbc.password = 123456
mybatis-config.xml , mybatis 核心配置文件
<?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>
<!-- 导入jdbc配置资源-->
<properties resource="jdbc.properties"/>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 开启log4j来记录日志 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="test">
<environment id="test">
<!-- 使用jdbc管理事务 , MANAGER 是使用mybatis管理事务-->
<transactionManager type="JDBC"></transactionManager>
<!--开启连接池 , UNPOOLED 不开启-->
<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>
<!-- 加载映射文件 ,加载mapper文件夹下所有-->
<mappers>
<mapper resource="mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
- 注意:如果
mapper/*.xml
报错,把*改成具体的mapper.xml文件名称,具体原因尚未明确
2.4 创建与数据库对应的实体类
package com.it.pojo;
public class User {
private long id;
private String name;
private int age;
private String sex;
private String address;
private String email;
public User(long id, String name, int age, String sex, String address, String email) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
this.email = email;
}
public User() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
2.5 创建数据操作持久层接口
package com.it.dao;
import com.it.pojo.User;
import java.util.Collection;
@Mapper
public interface UserDao {
Collection<User> findAll();
User findById(long id);
void save(User user);
void update(User user);
void delete(long id);
}
2.5-1 补充 创建数据操作持久层接口实现配置文件UserMapper.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="com.it.dao.UserDao">
<select id="findAll" resultType="com.it.pojo.User">
select * from user
</select>
<select id="findById" resultType="com.it.pojo.User">
select * from user where id = #{id}
</select>
<insert id="save">
insert into user value(#{id},#{name},#{age},#{sex},#{address},#{email})
</insert>
<update id="update">
update user set name = #{name} where id = #{id}
</update>
<delete id="delete">
delete from user where id = #{id}
</delete>
</mapper>
2.6 创建测试类,测试
package com.it.test;
import com.it.dao.UserDao;
import com.it.pojo.User;
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;
import java.util.Collection;
public class Test01 {
static SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
static UserDao userDao;
public static void findAll(){
Collection<User> all = userDao.findAll();
System.out.println("查询所有结果");
System.out.println("---------------------------------");
for (User user:all){
System.out.println(user.toString());
}
}
public static void findById(){
User user = userDao.findById(1);
System.out.println("查询所有结果");
System.out.println("---------------------------------");
System.out.println(user.toString());
}
public static void save(){
User user = new User(3,"ls",22,"男","llll.","000000");
userDao.save(user);
System.out.println("新增数据"+user.toString()+"成功");
}
public static void update(){
User user = new User(2,"zhangs",22,null,"","");
userDao.update(user);
System.out.println("修改数据"+user.toString()+"成功");
}
public static void delete(){
userDao.delete(2);
System.out.println("删除成功");
}
public static void main(String[] args) {
SqlSession session=null;
SqlSessionFactory factory = null;
try {
factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
session = factory.openSession();
userDao = session.getMapper(UserDao.class);
System.out.println("============================");
findAll();
System.out.println("============================");
findById();
System.out.println("============================");
save();
findAll();
System.out.println("============================");
update();
findAll();
System.out.println("============================");
delete();
findAll();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (session!=null){
session.commit();
session.close();
}
}
}
}
2.7 基于注解开发修改
修改dao层的代码,创建数据操作接口
package com.it.dao;
import com.it.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.Collection;
/**
* 使用注解执行sql
* @author ZRY
* @version 1.0
*/
public interface UserDao1 {
@Select("select * from user")
Collection<User> findAll();
@Select("select * from user where id = #{id}")
User findById(long id);
@Insert("insert into user value(#{id},#{name},#{age},#{sex},#{address},#{email})")
void save(User user);
@Update(" update user set name = #{name} where id=#{id}")
void update(User user);
@Delete("delete from user where id=#{id}")
void delete(long id);
}
修改核心配置文件,mybatis-config.xml
新增<mapper class="com.it.dao.UserDao1"/>
<?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>
<!-- 导入jdbc配置资源-->
<properties resource="jdbc.properties"/>
<environments default="test">
<environment id="test">
<!-- 使用jdbc管理事务 , MANAGER 是使用mybatis管理事务-->
<transactionManager type="JDBC"></transactionManager>
<!--开启连接池 , UNPOOLED 不开启-->
<dataSource type="POOLED">
<property name="dirver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 ,加载mapper文件夹下所有-->
<mappers>
<!-- 基于xml配置文件的-->
<mapper resource="mapper/UserMapper.xml"></mapper>
<!-- 基于注解的,需要绑定类-->
<mapper class="com.it.dao.UserDao1"/>
</mappers>
</configuration>
2.6 创建测试类,测试基于注解的mybatis开发
package com.it.test;
import com.it.dao.UserDao;
import com.it.dao.UserDao1;
import com.it.pojo.User;
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;
import java.util.Collection;
public class Test02 {
static SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
static UserDao1 userDao1;
public static void findAll(){
Collection<User> all = userDao1.findAll();
System.out.println("查询所有结果");
System.out.println("---------------------------------");
for (User user:all){
System.out.println(user.toString());
}
}
public static void findById(){
User user = userDao1.findById(1);
System.out.println("查询所有结果");
System.out.println("---------------------------------");
System.out.println(user.toString());
}
public static void save(){
User user = new User(2,"ls",22,"男","llll","");
userDao1.save(user);
System.out.println("新增数据"+user.toString()+"成功");
}
public static void update(){
User user = new User(3,"zhangs",22,null,"","");
userDao1.update(user);
System.out.println("修改数据"+user.toString()+"成功");
}
public static void delete(){
userDao1.delete(2);
System.out.println("删除成功");
}
public static void main(String[] args) {
SqlSession session=null;
SqlSessionFactory factory = null;
try {
factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
session = factory.openSession();
userDao1 = session.getMapper(UserDao1.class);
System.out.println("============================");
findAll();
System.out.println("============================");
findById();
System.out.println("============================");
save();
findAll();
System.out.println("============================");
update();
findAll();
System.out.println("============================");
delete();
findAll();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (session!=null){
session.commit();
session.close();
}
}
}
}