内容 | 说明 | 重要程度 |
---|---|---|
Mybatis框架介绍 | 介绍框架与Mybatis的概念 | ?? |
Mybatis开发流程 | 详细讲解mybatis六步开发流程 | ????? |
Mybatis使用细则 | 讲解mybatis开发中的各种细节 | ????? |
Mybatis工作流程 | 讲解mybatis的内部执行过程 | ??? |
1.软件开发中的框架
框架是可被应用开发者定制的应用骨架
框架是一种规则,保证开发者遵循相同的方式开发程序
框架提倡“不要重复造轮子”,对基础功能进行封装
2.框架的优点
极大提高了开发效率
统一的编码规则,利于团队管理
灵活配置的应用,拥有更好的维护性
3.SSM开发框架
Spring Spring MVC Mybatis
1.Mybatis是最优秀持久层框架(dao)
2.Mybatis使用XML将SQL与程序解耦,便于维护
3.Mybatis学习简单,执行高效,是JDBC的延伸
Mybatis中文文档 https://mybatis.org/mybatis-3/zh/index.html
1.引入Mybatis依赖
2.创建核心配置文件
3.创建实体(Entity)类
4.创建Mapper映射文件
5.初始化SessionFactory
6.利用SqlSession对象操作数据
单元测试是指对软件中的最小可测试单元进行核查和验证
测试用例是指编写一段代码对已有的功能(方法)进行核验
JUnit4是java中最著名的单元测试工具,主流IDE内置支持
JUnit是JUnit的第4代版本
JUnit4使用方法
1.引入JUnit Jar包或增加Maven依赖
2.编写测试用例验证目标方法是否正确运行
3.在测试用例上增加@Test注解开始单元测试
//junit4.12 maven依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
核心文件:mybatis-config.xml
Mybatis采用XML格式配置数据库环境信息
Mybatis环境配置标签<environment>
environment包含数据库驱动、URL、用户名与密码
<!--配置环境,不同的环境 不同的id名字-->
<environment id="dev">
<!--采用JDBC方式对数据库事务进行commit/rollback-->
<transactionManager type="JDBC"></transactionManager>
<!--采用连接池方式管理数据库连接-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/babytun?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
<!--采用maven的方式增加依赖 写在pom.xml中-->
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
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>
<!--设置默认指向的数据库-->
<environments default="dev">
<environment id="dev">
<!--采用JDBC方式对数据库事务进行commit/rollback-->
<transactionManager type="JDBC"></transactionManager>
<!--采用连接池方式管理数据库连接-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/babytun?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
1.SqlSessionFactory是Mybatis的核心对象
2.用于初始化Mybatis,创建SqlSession对象
3.保证SqlSessionFactory在应用中全局唯一
1.SqlSession是Mybatis操作数据库的核心对象
2.SqlSession使用JDBC方式与数据库交互
3.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 MybatisTestor {
@Test
public void testSqlSessionFactory() throws IOException {
//利用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("SqlSessionFactory加载成功");
SqlSession sqlSession=null;
try{
//创建SqlSession对象,SqlSession是JDBC的扩展类,用于与数据库交互
sqlSession =sqlSessionFactory.openSession();
//创建数据库连接(测试用)
Connection connection=sqlSession.getConnection();
System.out.println(connection);
}catch (Exception e){
e.printStackTrace();
}finally {
if (sqlSession!=null){
//如果type="POOLED",代表使用连接池,close则是将连接回收到连接池
//如果type="UNPOOLED",代表直连,close则会调用Connection.close()方法关闭
sqlSession.close();
}
}
}
}
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;
/**
* MybatisUtils工具类,创建全局唯一的SqlSessionFactory对象
*/
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);
}
}
/**
* openSession 创建一个新的SqlSession对象
* @return SqlSession对象
*/
public static SqlSession openSession(){
return sqlSessionFactory.openSession();
}
/**
* 释放一个有效的SqlSession对象
* @param session 准备释放SqlSession对象
*/
public static void closeSession(SqlSession session){
if(session!=null){
session.close();
}
}
}
1.创建实体类(Entity)
2.创建Mapper XML
3.编写<select> SQL标签
4.开启驼峰命名映射
5.新增<mapper>
6.SqlSession执行select语句
public class Goods {
private Integer goodsId;
private String title;
private String subTitle;
private Float originalCost;
private Float currentPrice;
private Float discount;
private Integer isFreeDelivery;
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;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="goods">
</mapper>
<select id="selectAll" resultType="com.xiaofeng.mybatis.entity.Goods">
select * from t_goods order by goods_id asc limit 10
</select>
<!--mybatis-config.xml 下的configuration标签中添加这段代码 开启驼峰命名-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--mybatis-config.xml 下的configuration标签中添加这段代码-->
<mappers>
<mapper resource="mappers/goods.xml"/>
</mappers>
@Test
public void testSelectAll(){
SqlSession session=null;
try{
session= MybatisUtils.openSession();
//主要看这里
List<Goods> list=session.selectList("goods.selectAll");
for (Goods g:list){
System.out.println(g.getTitle());
}
}catch (Exception e){
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
<!-- 单参数传递,使用parameterType指定参数的数据类型即可, SQL中的#{value}提取参数 -->
<select id="selectById" parameterType="Integer" resultType="com.xiaofeng.mybatis.entity.Goods">
select * from t_goods where goods_id=#{value}
</select>
@Test
public void testSelectById(){
SqlSession session=null;
try{
session= MybatisUtils.openSession();
//看这里
Goods goods=session.selectOne("goods.selectById",739);
System.out.println(goods.getTitle());
}catch (Exception e){
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
<!--多参数传递时,使用parameterType指定Map接口, SQL中的#{key}提取参数 -->
<select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.xiaofeng.mybatis.entity.Goods">
select * from t_goods
where current_price between #{min} and #{max}
order by current_price
limit 0 ,#{limt}
</select>
@Test
public void testSelectByPriceRange(){
SqlSession session=null;
try{
session= MybatisUtils.openSession();
//看这里
Map param=new HashMap();
param.put("min",100);
param.put("max",500);
param.put("limt",10);
List<Goods> list=session.selectList("goods.selectByPriceRange",param);
for (Goods g:list){
System.out.println(g.getTitle()+":"+g.getCurrentPrice());
}
}catch (Exception e){
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
<!-- select id="selectGoodsMap" resultType="java.util.Map" 返回结果乱序-->
<!--LinkedHashMap 返回结果有序-->
<!--利用LinkedHashMap保存多表关联结果
Mybatis会将每一条记录包装为LinkedHashMap对象
key是字段名,value是字段所对应的值,字段类型根据表结构进行自动判断
优点:易于扩展,易于使用
缺点:太过灵活,无法进行编译时检查
-->
<select id="selectGoodsMap" resultType="java.util.LinkedHashMap">
select g.*,c.category_name from t_goods g,t_category c
where g.category_id=c.category_id
</select>
@Test
public void testSelectGoodsMap(){
SqlSession session=null;
try{
session= MybatisUtils.openSession();
//看这里
List<Map> list=session.selectList("goods.selectGoodsMap");
for (Map map:list){
System.out.println(map);
}
}catch (Exception e){
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
1.ResultMap可以将查询结果映射为复杂类型的Java对象
2.ResultMap适用于Java对象保存多表关联结果
3.ResultMap支持对象关联查询等高级特性
<!--结果映射-->
<resultMap id="rmGoods" type="com.xiaofeng.mybatis.dto.GoodsDTO">
<!--设置主键字段与属性映射-->
<id property="goods.goodsId" column="goods_id"></id>
<!--设置非主键字段与属性映射-->
<result property="goods.title" column="title"></result>
<result property="goods.subTitle" column="sub_title"></result>
<result property="goods.originalCost" column="original_cost"></result>
<result property="goods.currentPrice" column="current_price"></result>
<result property="goods.discount" column="discount"></result>
<result property="goods.isFreeDelivery" column="is_free_delivery"></result>
<result property="goods.categoryId" column="category_id"></result>
<result property="categoryName" column="category_name"></result>
<result property="test" column="test"></result>
</resultMap>
<select id="selectGoodsDTO" resultMap="rmGoods" resultType="java.util.LinkedHashMap">
select g.*,c.category_name,‘1‘ as test from t_goods g,t_category c
where g.category_id=c.category_id
</select>
import com.xiaofeng.mybatis.entity.Goods;
//Data Transfer Object 数据传输对象
public class GoodsDTO {
private Goods goods=new Goods();
private String categoryName;
private String test;
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@Test
public void testSelectGoodsDTO(){
SqlSession session=null;
try{
session= MybatisUtils.openSession();
//看这里
List<GoodsDTO> list=session.selectList("goods.selectGoodsDTO");
for (GoodsDTO g:list){
System.out.println(g.getGoods().getTitle());
}
}catch (Exception e){
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
两张表
//category实体类
public class Category {
private Integer categoryId;
private String categoryName;
private Integer parentId;
private Integer categoryLevel;
private Integer categoryOrder;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getCategoryLevel() {
return categoryLevel;
}
public void setCategoryLevel(Integer categoryLevel) {
this.categoryLevel = categoryLevel;
}
public Integer getCategoryOrder() {
return categoryOrder;
}
public void setCategoryOrder(Integer categoryOrder) {
this.categoryOrder = categoryOrder;
}
}
<!--结果映射-->
<resultMap id="rmGoods" type="com.xiaofeng.mybatis.dto.GoodsDTO">
<!--设置主键字段与属性映射-->
<id property="goods.goodsId" column="goods_id"></id>
<!--设置非主键字段与属性映射-->
<!--goods-->
<result property="goods.title" column="title"></result>
<result property="goods.subTitle" column="sub_title"></result>
<result property="goods.originalCost" column="original_cost"></result>
<result property="goods.currentPrice" column="current_price"></result>
<result property="goods.discount" column="discount"></result>
<result property="goods.isFreeDelivery" column="is_free_delivery"></result>
<result property="goods.categoryId" column="category_id"></result>
<!--Category-->
<result property="category.categoryId" column="category_id"></result>
<result property="category.categoryName" column="category_name"></result>
<result property="category.parentId" column="parent_id"></result>
<result property="category.categoryLevel" column="category_level"></result>
<result property="category.categoryOrder" column="category_order"></result>
<result property="test" column="test"></result>
</resultMap>
<select id="selectGoodsDTO" resultMap="rmGoods" resultType="java.util.LinkedHashMap">
select g.*,c.*,‘1‘ as test from t_goods g,t_category c
where g.category_id=c.category_id
</select>
@Test
public void testSelectGoodsDTO(){
SqlSession session=null;
try{
session= MybatisUtils.openSession();
//看这里
List<GoodsDTO> list=session.selectList("goods.selectGoodsDTO");
for (GoodsDTO g:list){
System.out.println(g.getGoods().getTitle());
}
}catch (Exception e){
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
import com.xiaofeng.mybatis.entity.Category;
import com.xiaofeng.mybatis.entity.Goods;
//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;
}
}
数据库事务是保证数据操作完整性的基础
| MySQL |
| 事务日志 数据表 |
客户端--------> | 新增日志1 数据1 |
| 新增日志2 commit------> 数据2 |
| 新增日志3 <-----rollback 数据3 |
插入 ------ <insert>
更新 ------ <update>
删除 ------ <delete>
新增 -<insert>
<insert id="insert" parameterType="com.xiaofeng.mybatis.entity.Goods">
INSERT INTO babytun.t_goods( title, sub_title, original_cost, current_price, discount, is_free_delivery, category_id)
VALUES (#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},#{isFreeDelivery},#{categoryId});
<selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">
-- 当前连接中最后产生的id号
select last_insert_id();
</selectKey>
</insert>
@Test
public void testInsert() {
SqlSession session = null;
try {
session = MybatisUtils.openSession();
//看这里
Goods goods = new Goods();
goods.setTitle("测试数据");
goods.setSubTitle("测试子标题");
goods.setOriginalCost(300f);
goods.setCurrentPrice(200f);
goods.setDiscount(0.7f);
goods.setIsFreeDelivery(0);
goods.setCategoryId(44);
//insert()方法返回值代表本次成功插入的记录总数
int num = session.insert("goods.insert", goods);
session.commit();//提交事务数据
System.out.println(goods.getGoodsId());
} catch (Exception e) {
if(session !=null) {
session.rollback();//回滚事务
}
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
<insert id="insert" parameterType="com.xiaofeng.mybatis.entity.Goods">
INSERT INTO SQL语句
<selectKey resultType="Integer" keyProperty="goodsId" order="AFTER">
-- 当前连接中最后产生的id号
select last_insert_id();
</selectKey>
</insert>
<insert id="insert" parameterType="com.xiaofeng.mybatis.entity.Goods"
useGeneratedKeys="true" keyProperty="goodsId" keyColumn="goods_id">
INSERT INTO SQL语句
</insert>
1)显示与隐式
1.selectKey标签需要明确编写获取最新主键的SQL语句
2.useGeneratedKeys属性会自动根据驱动生成对应的SQL语句
2)应用场景不同
1.selectKey适用于使用的关系型数据库
2.useGeneratedKeys只支持"自增主键"类型的数据库
3)总结
1.selectKey标签是通用方案,适用于所有数据库,但编写麻烦
2.useGeneratedKeys属性只支持"自增主键"类型的数据库,使用简单 ---->个人推荐这个
<insert id="insert" parameterType="com.xiaofeng.mybatis.entity.Goods">
INSERT INTO SQL语句
<selectKey resultType="Integer" keyProperty="goodsId" order="BEFORE">
SELECT seq_goods.nextval as id from dual;
</selectKey>
</insert>
<update id="update" parameterType="com.xiaofeng.mybatis.entity.Goods">
UPDATE babytun.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}
</update>
@Test
public void testUpdate() throws Exception {
SqlSession session = null;
try {
session = MybatisUtils.openSession();
//看这里
Goods goods=session.selectOne("goods.selectById",12679);
goods.setIsFreeDelivery(1);
//update()方法返回值代表本次成功修改的记录总数
int num = session.update("goods.update", goods);
session.commit();//提交事务数据
} catch (Exception e) {
if(session !=null) {
session.rollback();//回滚事务
}
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
<delete id="delete" parameterType="Integer">
delete from t_goods where goods_id = #{value}
</delete>
@Test
public void testDelete() throws Exception {
SqlSession session = null;
try {
session = MybatisUtils.openSession();
//看这里
//delete()方法返回值代表本次成功删除的记录总数
int num = session.delete("goods.delete", 12679);
session.commit();//提交事务数据
} catch (Exception e) {
if(session !=null) {
session.rollback();//回滚事务
}
e.printStackTrace();
} finally {
MybatisUtils.closeSession(session);
}
}
SQL注入是指攻击者利用SQL漏洞,绕过系统约束,越权获取数据的攻击方式
SQL代码:"select * from a where name=‘" +name+"‘";
正常情况:
name:张三 -> select * from a where name=‘张三‘;
SQL注入攻击:
name: ‘or 1=1 or 1=‘ -> select * from a where name=‘‘ or 1=1 or 1=‘‘;
1.${} 文本替换,未经任何处理对SQL文本替换(原文传值)
2.#{} 预编译传值,使用预编译传值可以预防SQL注入
Session Close
/ |
应用 ---> mybatis-config.xml ---> SqlSessionFactory ---> SqlSession ---> insert | update | delete | select
| | | | |
| | bullid() | | |
\/ \/ \/ \/ \/
全局设置项 SqlSessionFactoryBulider mapper.xml commit rollback
环境配置
mapper声明
原文:https://www.cnblogs.com/xiaofengrong/p/14771934.html