MyBatis是优秀的持久层框架
MyBatis使用XML将SQL与程序解耦,便于维护
MyBatis学习简单,执行高效,是JDBC的延伸
MyBatis官方文档
MyBatis开发流程https://mybatis.org/mybatis-3/zh/index.html
JUnit4单元测试工具
- 引入MyBatis依赖
- 创建核心配置文件
- 创建实体(Entity)类
- 创建Mapper映射文件
- 初始化SessionFactory
- 利用SqlSession对象操作数据
JUnit4使用方法单元测试是指对软件中的最小可测试单元进行检查和验证
测试用例是指编写一段代码对已有功能(方法)进行校验
JUnit 4是Java中最著名的单元测试工具,主流IDE内置支持
JUnit4测试案例引入JUnit Jar包或增加Maven依赖
编写测试用例验证目标方法是否正确运行
在测试用例上增加@Test注解开始单元测试
junit junit 4.12
// 四则运算功能实现类
public class Calculator {
// 加法运算
public int add(int a, int b){
return a + b;
}
// 减法运算
public int subtract(int a, int b){
return a - b;
}
// 乘法运算
public int multiply(int a, int b){
return a * b;
}
// 除法运算
public float divide(int a, int b){
if (b==0){
throw new ArithmeticException("除数不能为0");
}
return (a*1f) / b;
}
}
// 测试类
public class CalculatorTest {
private Calculator cal = new Calculator();
// 命名规则:
// 1. 与原方法保持一致
// 2. 在原方法前增加test前缀
@Test
public void testAdd(){
int result = cal.add(1, 2);
System.out.println(result);
}
@Test
public void testSubtract(){
int result = cal.subtract(1, 2);
System.out.println(result);
}
@Test
public void testMultiply(){
int result = cal.multiply(1, 2);
System.out.println(result);
}
@Test
public void testDivide(){
float result = cal.divide(1, 2);
System.out.println(result);
}
}
MyBatis配置文件
一般使用mybatis-config.xml进行配置:
MyBatis采用XML格式配置数据库环境信息
MyBaits环境配置标签
environment包含数据库驱动、URL、用户名与密码
SqlSessionFactoryorg.mybatis mybatis 3.5.10
SqlSessionSqlSessionFactory是MyBatis的核心对象
用于初始化MyBatis,创建SqlSession对象
保证SqlSessionFactory在应用中全局唯一
SqlSession是MyBatis操作数据库的核心对象
SqlSession使用JDBC方式与数据库交互
SqlSession对象提供了数据表CRUD对应方法
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 java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
public class MyBatisTester {
@Test
public void testSqlSessionFactory() throws IOException {
// 默认从当前的类路径下以字符流的形式加载mybatis-config.xml配置文件, 利用Reader加载classpath下的mybatis-config.xml核心配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 初始化SqlSessionFactory对象,同时解析mybatis-config.xml文件
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
System.out.println("SessionFactory加载成功");
SqlSession sqlSession = null;
try {
// 创建SqlSession对象,SqlSession是JDBC的扩展类,用于与数据库交互
sqlSession = sqlSessionFactory.openSession();
// 创建数据库连接(测试用)
Connection connection = sqlSession.getConnection();
System.out.println(connection);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if (sqlSession != null){
// 如果type="POOLED",代表使用连接池,close则是将连接回收到连接池中
// 如果type="UNPOOLED",代表直连,close则会调用Connection.close()方法关闭连接
sqlSession.close();
}
}
}
}
MyBatisUtils工具类
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.io.Reader;
public class MyBatisUtils {
// 利用static(静态)属于类不属于对象,且全局唯一
private static SqlSessionFactory sqlSessionFactory = null;
// 利用静态块在初始化类时实例化sqlSessionFactory
static {
Reader reader = null;
try {
reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
// 初始化错误时,通过抛出异常ExceptionInInitializerError通知调用者
throw new ExceptionInInitializerError(e);
}
}
public static SqlSession openSession(){
return sqlSessionFactory.openSession();
}
public static void closeSession(SqlSession session){
if (session != null){
session.close();
}
}
// 测试方法代码
@Test
public void testMyBatisUtils(){
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtils.openSession();
Connection connection = sqlSession.getConnection();
System.out.println(connection);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
MyBatisUtils.closeSession(sqlSession);
}
}
MyBatis数据查询
查询步骤:
- 创建实体类(Entity)
- 创建Mapper XML
- 编写
SQL标签 - 开启驼峰命名映射
- 新增
- SqlSession执行select语句
//1. 创建实体类(Entity)
public class Goods {
private Integer goodsId; //商品编号
private String title; //标题
private String subTitle; //子标题
private Float originalCost; //原始价格
private Float currentPrice; //当前价格
private Float discount; //折扣率
private Integer isFreeDelivery; //是否包邮,1-包邮 0-不包邮
private Integer categoryId; //分类编号
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubTitle() {
return subTitle;
}
public void setSubTitle(String subTitle) {
this.subTitle = subTitle;
}
public Float getOriginalCost() {
return originalCost;
}
public void setOriginalCost(Float originalCost) {
this.originalCost = originalCost;
}
public Float getCurrentPrice() {
return currentPrice;
}
public void setCurrentPrice(Float currentPrice) {
this.currentPrice = currentPrice;
}
public Float getDiscount() {
return discount;
}
public void setDiscount(Float discount) {
this.discount = discount;
}
public Integer getIsFreeDelivery() {
return isFreeDelivery;
}
public void setIsFreeDelivery(Integer isFreeDelivery) {
this.isFreeDelivery = isFreeDelivery;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
// 6. SqlSession执行select语句
@Test
public void testSelectAll() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
List list = session.selectList("goods.selectAll");
for (Goods g : list){
System.out.println(g.getTitle());
}
} catch (Exception e) {
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
MyBatis的SQL参数传递
// 测试类文件内容
@Test
public void testSelectById() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
Goods goods = session.selectOne("goods.selectById", 1602);
System.out.println(goods.getTitle());
} catch (Exception e) {
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
@Test
public void testSelectByPriceRange() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
Map param = new HashMap();
param.put("min", 100);
param.put("max", 500);
param.put("limit", 10);
List list = session.selectList("goods.selectByPriceRange", param);
for (Goods g : list){
System.out.println(g.getTitle());
}
} catch (Exception e) {
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
MyBatis多表关联查询
select g.*, c.category_name from t_goods g , t_category c
where g.category_id = c.category_id
// 测试类文件方法内容
@Test
public void testSelectGoodsMap() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
List
ResultMap结果映射
ResultMap可以将查询结果映射为复杂类型的Java对象
ResultMap适用于Java对象保存多表关联结果
ResultMap支持对象关联查询等高级特性
select g.*, c.category_name, '1' as test from t_goods g , t_category c
where g.category_id = c.category_id
// DTO类,用于多表联合查询
// Data Transfer Object--数据传输对象
public class GoodsDTO {
private Goods goods = new Goods();
private Category category = new Category();
private String test;
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
// 测试类文件内容
@Test
public void testSelectGoodsDTO() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
List list = session.selectList("goods.selectGoodsDTO");
for (GoodsDTO g : list){
System.out.println(g.getGoods().getTitle());
}
} catch (Exception e) {
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
MyBatis对数据库的写入操作
insert插入数据
INSERT INTO t_goods(title,sub_title,original_cost,current_price, discount, is_free_delivery) VALUES (#{title}, #{subTitle}, #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}) select last_insert_id()
// 测试类文件内容
@Test
public void testInsert() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
Goods goods = new Goods();
goods.setTitle ("测试商品");
goods.setSubTitle ("测试子标题");
goods.setOriginalCost(200f);
goods.setCurrentPrice(100f);
goods .setDiscount(0.5f);
goods.setIsFreeDelivery (1);
goods.setCategoryId (43);
// insert()方法返回值代表本次成功插入的记录总数
int num = session.insert("goods.insert", goods);
session.commit(); // 提交事务数据
System.out.println(goods.getGoodsId());
} catch (Exception e) {
if (session != null){
session.rollback(); // 回滚事务
}
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
selectKey和useGenerateKeys的区别
selectKey标签需要明确编写获取最新主键的SQL语句
useGeneratedKeys属性会自动根据驱动生成对应SQL语句
selectKey适用于所有的关系型数据库
useGeneratedKeys只支持"自增主键"类型的数据库
selectKey标签是通用方案,适用于所有数据库,但编写麻烦
useGeneratedKeys属性只支持"自增主键"数据库,使用简单
MyBatis的更新与删除INSERT INTO t_goods(title,sub_title,original_cost,current_price, discount, is_free_delivery) VALUES (#{title}, #{subTitle}, #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery})
UPDATE t_goods SET title = #{title} , sub_title = #{ subTitle} , original_cost = #{originalCost} , current_price = #{currentPrice} , discount = #{discount} , is_free_delivery = #{isFreeDelivery} , category_id = #{categoryId} WHERe goods_id = #{goodsId} delete from t_goods where goods_id = #{value}
// 测试类文件内容
@Test
public void testUpdate() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
Goods goods = session.selectOne("goods.selectById", 739);
goods.setTitle("更新测试商品");
int num = session.update("goods.update", goods);
session.commit(); // 提交事务数据
} catch (Exception e) {
if (session != null){
session.rollback(); // 回滚事务
}
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
@Test
public void testDelete() throws Exception {
SqlSession session = null;
try {
session = MyBatisUtils.openSession();
int num = session.delete("goods.delete", 739);
session.commit(); // 提交事务数据
} catch (Exception e) {
if (session != null){
session.rollback(); // 回滚事务
}
throw e;
} finally {
MyBatisUtils.closeSession(session);
}
}
MyBatis预防SQL注入攻击
MyBatis工作流程MyBatis两种传值方式
${}文本替换,未经任何处理对SQL文本替换
#{}预编译传值,使用预编译传值可以预防SQL注入



