截屏2022-07-21 17.10.09.png
官網(wǎng):https://mybatis.org/mybatis-3/zh/index.html
截屏2022-07-21 17.11.48.png
1、MyBatis開發(fā)流程六步驟
截屏2022-07-21 17.24.29.png
2历筝、MyBatis使用細(xì)則
截屏2022-07-22 09.19.40.png
截屏2022-07-22 09.23.11.png
截屏2022-07-22 11.19.35.png
截屏2022-07-22 11.22.12.png
截屏2022-07-22 14.56.41.png
截屏2022-07-22 16.07.48.png
截屏2022-07-22 15.29.25.png
截屏2022-07-22 16.55.36.png
截屏2022-07-22 下午9.57.20.png
截屏2022-07-22 下午9.57.41.png
截屏2022-07-22 下午9.48.21.png
截屏2022-07-22 下午9.48.54.png
截屏2022-07-22 下午9.42.48.png
截屏2022-07-22 下午9.43.58.png
截屏2022-07-22 下午9.45.07.png
截屏2022-07-22 下午9.47.20.png
截屏2022-07-22 下午10.04.38.png
截屏2022-07-22 下午10.12.24.png
截屏2022-07-22 下午10.15.38.png
MybatisUtils.java工具類:
/**
* MybatisUtils工具類酗昼,創(chuàng)建全局唯一的SqlSessionFactory對(duì)象
*/
public class MybatisUtils {
//利用static(靜態(tài))屬于類不屬于對(duì)象,且全局唯一
private static SqlSessionFactory sqlSessionFactory = null;
//利用靜態(tài)塊在初始化類是實(shí)例化sqlSessionFactory
static {
Reader reader = null;
try {
reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
//初始化錯(cuò)誤時(shí)梳猪,通過拋出異常ExceptionInInitializerError通知調(diào)用者
throw new ExceptionInInitializerError(e);
}
}
/**
* openSession創(chuàng)建一個(gè)新的SqlSession對(duì)象
* @return SqlSession對(duì)象
*/
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
/**
* 釋放一個(gè)有效的SqlSession對(duì)象
* @param session 準(zhǔn)備釋放SqlSession對(duì)象
*/
public static void closeSession(SqlSession session) {
if (session != null) {
session.close();
}
}
}
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>
<settings>
<!-- goods_id == goodsId 駝峰命名轉(zhuǎn)換-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 設(shè)置默認(rèn)指向的數(shù)據(jù)庫(kù)-->
<environments default="dev">
<!-- 配置環(huán)境麻削,不同的環(huán)境不同的id名字-->
<environment id="dev">
<!-- 采用JDBC方式對(duì)數(shù)據(jù)庫(kù)事務(wù)進(jìn)行commit/rollback-->
<transactionManager type="JDBC"></transactionManager>
<!-- 采用連接池方式管理數(shù)據(jù)庫(kù)連接-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/babytun?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mappers/goods.xml"/>
</mappers>
</configuration>
goods.xml創(chuàng)建Mapper 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="goods">
<select id="selectAll" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods order by goods_id desc limit 10
</select>
<!-- 單參數(shù)傳遞,使用parameterType指定參數(shù)的數(shù)據(jù)類型即可舔示,SQL中#{value}提取參數(shù)-->
<select id="selectById" parameterType="Integer" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods where goods_id = #{value}
</select>
<!-- 多參數(shù)傳遞時(shí)碟婆,使用parameterType指定Map接口,SQL中#{key}提取參數(shù)-->
<select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods
where
current_price between #{min} and #{max}
order by current_price
limit 0,#{limit}
</select>
<!-- 利用LinkedHashMap保存多表關(guān)聯(lián)結(jié)果
MyBatis會(huì)將每一條記錄包裝為L(zhǎng)inkedHashMap對(duì)象
key是字段名 value是字段對(duì)應(yīng)的值惕稻,字段類型根據(jù)表結(jié)構(gòu)進(jìn)行自行判斷
優(yōu)點(diǎn):易于擴(kuò)展竖共,易于使用
缺點(diǎn):太過靈活,無法進(jìn)行編譯時(shí)檢查
-->
<select id="selectGoodsMap" resultType="java.util.LinkedHashMap">
select g.*,c.category_name from t_goods g join t_category c on g.category_id = c.category_id
</select>
<!-- 結(jié)果映射-->
<resultMap id="rmGoods" type="com.imooc.mybatis.dto.GoodsDTO">
<!-- 設(shè)置主鍵字段與屬性映射-->
<id property="goods.goodsId" column="goods_id"></id>
<!-- 設(shè)置非主鍵字段與屬性映射-->
<result property="goods.title" column="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=" " resultMap="rmGoods">
select g.*,c.category_name,'1' as test from t_goods g join t_category c on g.category_id = c.category_id
</select>
<insert id="insert" parameterType="com.imooc.mybatis.entity.Goods"
useGeneratedKeys="true"
keyProperty="goodsId"
keyColumn="goods_id">
insert into 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="int" keyProperty="goodsId" order="AFTER">-->
<!-- <!– 當(dāng)前連接中最后產(chǎn)生的id號(hào)–>-->
<!-- select last_insert_id()-->
<!-- </selectKey>-->
</insert>
<update id="update" parameterType="com.imooc.mybatis.entity.Goods">
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}
</update>
<delete id="delete" parameterType="Integer">
delete from t_goods where goods_id = #{value}
</delete>
</mapper>
MyBatisTestor.java測(cè)試類:
public class MyBatisTestor {
@Test
public void testSqlSessionFactory() throws IOException {
//利用Reader加載classpath下的mybatis-config.xml核心配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//初始化SqlSessionFactory對(duì)象俺祠,同時(shí)解析mybatis-config.xml文件
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
System.out.println("sqlSessionFactory加載成功");
SqlSession sqlSession = null;
try {
//創(chuàng)建SqlSession對(duì)象公给,SqlSession是JDBC的擴(kuò)展類,用于與數(shù)據(jù)庫(kù)交互
sqlSession = sqlSessionFactory.openSession();
//創(chuàng)建數(shù)據(jù)庫(kù)連接(測(cè)試用)
Connection conn = sqlSession.getConnection();
System.out.println(conn);
}catch (Exception e) {
e.printStackTrace();
}finally {
if (sqlSession != null) {
//如果type="POOLED",代表使用連接池蜘渣,close則是將連接回收到連接池中
//如果type="UNPOOLED",代表直連淌铐,close則會(huì)調(diào)用Connection.close關(guān)閉連接
sqlSession.close();
}
}
}
@Test
public void testMyBatisUtils() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
Connection connection = sqlSession.getConnection();
System.out.println(connection);
} catch (Exception e) {
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testSelectAll() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
List<Goods> list = sqlSession.selectList("goods.selectAll");
for (Goods g : list) {
System.out.println(g.getTitle() + g.getSubTitle());
}
} catch (Exception e) {
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testselectById() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
Goods g = sqlSession.selectOne("goods.selectById",1903);
if (g != null) {
System.out.println(g.getTitle() + g.getSubTitle());
}else {
System.out.println("未找到您查找的數(shù)據(jù)");
}
} catch (Exception e) {
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testSelectByPriceRange() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
Map<String, Integer> param = new HashMap<>();
param.put("min",100);
param.put("max", 500);
param.put("limit", 1);
List<Goods> list = sqlSession.selectList("goods.selectByPriceRange", param);
for (Goods g : list) {
System.out.println(g.getTitle() + g.getSubTitle());
}
} catch (Exception e) {
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testSelectGoodsMap() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
List<Map > list = sqlSession.selectList("goods.selectGoodsMap");
for (Map map : list) {
System.out.println(map);
}
} catch (Exception e) {
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testSelectGoodsDTO() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
List<GoodsDTO> list = sqlSession.selectList("goods.selectGoodsDTO");
for (GoodsDTO goodsDTO : list) {
System.out.println(goodsDTO.getGoods().getTitle() + goodsDTO.getCategoryName());
}
} catch (Exception e) {
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testInsert() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
Goods goods = new Goods();
goods.setTitle("小狗子");
goods.setSubTitle("小狗子叫小黑");
goods.setOriginalCost(100F);
goods.setCurrentPrice(99F);
goods.setDiscount(1F);
goods.setIsFreeDelivery(0);
goods.setCategoryId(1);
//insert()返回值代表本次成功插入的記錄總數(shù)
int num = sqlSession.insert("goods.insert",goods);
System.out.println(num);
//提交事務(wù)數(shù)據(jù)
sqlSession.commit();
} catch (Exception e) {
if (sqlSession != null) {
sqlSession.rollback();//回滾事務(wù)
}
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testUpdate() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
Goods goods = sqlSession.selectOne("goods.selectById",1903);
goods.setTitle("二狗子");
//update()返回值代表本次成功更新的記錄總數(shù)
int num = sqlSession.update("goods.update",goods);
System.out.println(num);
//提交事務(wù)數(shù)據(jù)
sqlSession.commit();
} catch (Exception e) {
if (sqlSession != null) {
sqlSession.rollback();//回滾事務(wù)
}
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
@Test
public void testDelete() throws Exception {
SqlSession sqlSession = null;
try {
sqlSession = MybatisUtils.openSession();
//delete()返回值代表本次成功刪除的記錄總數(shù)
int num = sqlSession.delete("goods.delete",1903);
System.out.println(num);
//提交事務(wù)數(shù)據(jù)
sqlSession.commit();
} catch (Exception e) {
if (sqlSession != null) {
sqlSession.rollback();//回滾事務(wù)
}
throw e;
} finally {
MybatisUtils.closeSession(sqlSession);
}
}
}