一、持久化与ORM
二、Mybatis
2.1 Mybatis简介
2.2 Mybatis特点
- 基于SQL语法,简单易学
- 能了解底层封装过程,内部通过JDBC访问数据库的操作
- SQL语句封装在配置文件中,便于统一管理与维护,降低程序的耦合度
- 方便程序代码调试
2.3 搭建Mybatis开发环境
-
创建Maven工程,导入Mybatis依赖
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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.kgc</groupId> <artifactId>mybatis-demo01</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>mybatis-demo01 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>mybatis-demo01</finalName> </build> </project>
-
编写Mybatis核心配置文件(mybatis-config.xml)
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"> <!--Mybatis核心配置文件--> <configuration> <!--配置环境--> <properties resource="database.properties"></properties><!--引入外部配置文件--> <typeAliases> <package name="com.smbms.pojo"/><!--别名包扫描--> </typeAliases> <environments default="mysql"> <!--默认值,让环境读取的是mysql的环境,默认值要和环境id一致--> <environment id="mysql"> <!--事务管理器--> <transactionManager type="JDBC"></transactionManager> <!--数据源--> <dataSource type="POOLED"> <property name="driver" value="${driverClassName}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <!--加载映射文件--> <mapper resource="mybatis/mapper/UserMapper.xml"/> </mappers> </configuration>
-
创建实体类-POJO
javapackage com.smbms.pojo; import lombok.Data; import lombok.ToString; import java.util.Date; /** * @author: * @datetime: 2024/3/24 * @desc: */ @Data @ToString public class User { private long id; private String userCode; private String userName; private String userPassword; private int gender; private Date birthday; private String phone; private String address; private int userRole; }
-
创建SQL映射文件(mapper.xml)
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"> <!--专门用于处理User表的sql--> <!--namespace跟接口路径保持一致--> <mapper namespace = "com.smbms.mapper.UserMapper"> <!--<mapper namespace = "aaaa">--> <!--查询总条数--> <!--只有查询才有虚拟表,只有虚拟表才有resultType,增删改返回的就不是虚拟表,而是影响的行数,增删改不能写resultType--> <!--因为查询总条数期望返回的是一个数字,所以resultType里面填int,用int接收,这里有两种写法: 1、写别名,如"int" 2、写路径,如"java.lang.Integer"--> <select id="getCount" resultType="int"> SELECT COUNT(*) FROM SMBMS_USER </select> <!--插入--> <insert id="saveUser"> INSERT INTO SMBMS_USER(userCode,userName) VALUES('wahaha','娃哈哈') </insert> <!--更改--> <update id="updateUser"> UPDATE SMBMS_USER SET userName='华为' WHERE id=8 </update> <!--删除--> <delete id="deleteUser"> DELETE FROM SMBMS_USER WHERE id=5 </delete> <!--查询其中某条数据--> <select id="getUserById" resultType="User"> SELECT * FROM SMBMS_USER WHERE id=15 </select> <!--查询所有数据--> <select id="getAllUser" resultType="User"> SELECT * FROM SMBMS_USER </select> </mapper>
-
创建测试类:l读取核心配置文件****mybatis-config.xml
l 创建 SqlSessionFactory 对象,读取配置文件
l 创建 SqlSession 对象
l 调用 mapper 文件进行数据操作
java
package com.smbms.test;
import com.smbms.mapper.UserMapper;
import com.smbms.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 org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author:
* @datetime: 2024/3/24
* @desc:
*/
/*@Slf4j //可以省略sout输出的注解*/
public class UserTest {
/*把前三步封装成一个方法*/
public static SqlSessionFactory factory;
private static InputStream is;
static {
//1、定义mybatis核心配置文件的路径
String path = "mybatis/mybatis-config.xml";
//2、转字节流接收
try {
is = Resources.getResourceAsStream(path);
} catch (IOException e) {
throw new RuntimeException(e);
}
//3、创建SqlSessionFactory对象
factory = new SqlSessionFactoryBuilder().build(is);
}
private UserMapper userMapper;
//查询操作
/* @Test
public void getCount() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行查询操作
int count = sqlSession.selectOne("aaaa.getCount");
System.out.println("该表中一共有" + count + "条数据");
//6、关闭资源
sqlSession.close();
is.close();
}*/
@Test
public void getCountForMapper() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行查询操作
userMapper = sqlSession.getMapper(UserMapper.class);
int count = userMapper.getCount();
System.out.println("该表中一共有" + count + "条数据");
//6、关闭资源
sqlSession.close();
is.close();
}
//插入操作
/* @Test
public void testInsert() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行插入操作
int line = sqlSession.insert("aaaa.saveUser");
System.out.println(line > 0 ? "插入成功" : "插入失败");
//提交事务
//因为mybatis会自动关闭提交
sqlSession.commit();
//6、关闭资源
sqlSession.close();
is.close();
}*/
@Test
public void testInsert() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行插入操作
userMapper = sqlSession.getMapper(UserMapper.class);
int line = userMapper.saveUser();
System.out.println(line > 0 ? "插入成功" : "插入失败");
//提交事务
//因为mybatis会自动关闭提交
sqlSession.commit();
//6、关闭资源
sqlSession.close();
}
//更改操作
/* @Test
public void testUpdate() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行更改操作
int line = sqlSession.update("aaaa.updateUser");
System.out.println(line > 0 ? "更改成功" : "更改失败");
//提交事务
//因为mybatis会自动关闭提交
sqlSession.commit();
//6、关闭资源
sqlSession.close();
is.close();
}*/
@Test
public void testUpdate() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行更改操作
userMapper = sqlSession.getMapper(UserMapper.class);
int line = userMapper.updateUser();
System.out.println(line > 0 ? "更改成功" : "更改失败");
//提交事务
//因为mybatis会自动关闭提交
sqlSession.commit();
//6、关闭资源
sqlSession.close();
}
//删除操作
/* @Test
public void testDelete() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行删除操作
int line = sqlSession.delete("aaaa.deleteUser");
System.out.println(line > 0 ? "删除成功" : "删除失败");
//提交事务
//因为mybatis会自动关闭提交
sqlSession.commit();
//6、关闭资源
sqlSession.close();
is.close();
}*/
@Test
public void testDelete() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行删除操作
userMapper = sqlSession.getMapper(UserMapper.class);
int line = userMapper.deleteUser();
System.out.println(line > 0 ? "删除成功" : "删除失败");
//提交事务
//因为mybatis会自动关闭提交
sqlSession.commit();
//6、关闭资源
sqlSession.close();
}
//查询其中某条数据
@Test
public void getUserById() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行查询操作
userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById();
System.out.println(user);
//6、关闭资源
sqlSession.close();
is.close();
}
//查询所有数据
@Test
public void getAllUser() throws IOException {
//4、创建核心对象------SqlSession
SqlSession sqlSession = factory.openSession();
//5、执行查询操作
userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getAllUser();
userList.forEach(System.out::println);
//6、关闭资源
sqlSession.close();
is.close();
}
}
2.4 Mybatis框架优缺点
优点
- 与JDBC相比,减少了50%以上的代码量
- 是最简单的持久化框架,小巧并简单易学
- SQL代码从程序代码中彻底分离,可重用
- 提供XML标签,支持编写动态SQL
- 提供映射标签,支持对象与数据库的ORM字段映射
缺点
- SQL语句编写工作量大,对开发人员有一定要求
- 数据库移植性差