十四奏夫、MyBatis入門

截屏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&amp;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">-->
<!--            &lt;!&ndash; 當(dāng)前連接中最后產(chǎn)生的id號(hào)&ndash;&gt;-->
<!--            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);
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市蔫缸,隨后出現(xiàn)的幾起案子腿准,更是在濱河造成了極大的恐慌,老刑警劉巖拾碌,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吐葱,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡校翔,警方通過查閱死者的電腦和手機(jī)弟跑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來防症,“玉大人孟辑,你說我怎么就攤上這事∧枨茫” “怎么了锤躁?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵队秩,是天一觀的道長(zhǎng)趋厉。 經(jīng)常有香客問我旺韭,道長(zhǎng),這世上最難降的妖魔是什么指么? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任酝惧,我火速辦了婚禮榴鼎,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘晚唇。我一直安慰自己巫财,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布哩陕。 她就那樣靜靜地躺著平项,像睡著了一般。 火紅的嫁衣襯著肌膚如雪悍及。 梳的紋絲不亂的頭發(fā)上闽瓢,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音心赶,去河邊找鬼扣讼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛缨叫,可吹牛的內(nèi)容都是我干的椭符。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼耻姥,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼销钝!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起琐簇,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤蒸健,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后婉商,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體纵装,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年据某,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诗箍。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡癣籽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出滤祖,到底是詐尸還是另有隱情筷狼,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布匠童,位于F島的核電站埂材,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏汤求。R本人自食惡果不足惜俏险,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一严拒、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧竖独,春花似錦裤唠、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至竞膳,卻和暖如春航瞭,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背坦辟。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工刊侯, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人长窄。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓滔吠,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親挠日。 傳聞我的和親對(duì)象是個(gè)殘疾皇子疮绷,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容