最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MyBatis使用Map與POJO類實(shí)現(xiàn)CRUD操作的步驟詳解

 更新時(shí)間:2025年12月24日 10:08:51   作者:自在極意功。  
本文將通過(guò)實(shí)際案例,詳細(xì)講解在MyBatis中如何使用Map集合和POJO類兩種方式實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增刪改查操作,解決常見(jiàn)映射問(wèn)題,提高開(kāi)發(fā)效率,需要的朋友可以參考下

一、MyBatis簡(jiǎn)介與CRUD基礎(chǔ)

MyBatis是一款優(yōu)秀的持久層框架,它支持自定義SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。MyBatis避免了幾乎所有的JDBC代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集的工作。

1.1 傳統(tǒng)JDBC的問(wèn)題

在傳統(tǒng)JDBC編程中,我們經(jīng)常遇到以下問(wèn)題:

// JDBC中繁瑣的結(jié)果集處理
while(rs.next()) {
    User user = new User();
    user.setId(rs.getString("id"));
    user.setIdCard(rs.getString("idCard"));
    user.setUsername(rs.getString("username"));
    // ... 需要為每個(gè)屬性手動(dòng)賦值
    userList.add(user);
}

這種方式存在以下缺點(diǎn):

  1. 代碼冗余,每個(gè)字段都需要手動(dòng)映射
  2. 容易出錯(cuò),字段名寫(xiě)錯(cuò)會(huì)導(dǎo)致運(yùn)行時(shí)錯(cuò)誤
  3. 維護(hù)困難,表結(jié)構(gòu)變化時(shí)需要修改大量代碼

二、MyBatis中使用Map實(shí)現(xiàn)CRUD

2.1 使用Map進(jìn)行數(shù)據(jù)插入

Map集合提供了靈活的鍵值對(duì)存儲(chǔ)方式,適合不確定參數(shù)數(shù)量或臨時(shí)性的數(shù)據(jù)操作。

2.1.1 基礎(chǔ)Map傳參

@Test
public void testInsertCarByMap() {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    
    // 使用Map封裝前端傳遞的數(shù)據(jù)
    Map<String, Object> map = new HashMap<>();
    map.put("carNum", "11111");
    map.put("brand", "比亞迪漢");
    map.put("guidePrice", 10.0);
    map.put("produceTime", "2020-11-11");
    map.put("carType", "電車");
    
    // 執(zhí)行SQL插入操作
    int count = sqlSession.insert("insertCar", map);
    System.out.println("插入記錄數(shù):" + count);
    
    sqlSession.commit();
    sqlSession.close();
}

2.1.2 Mapper XML配置

<!-- CarMapper.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="com.example.mapper.CarMapper">
    
    <insert id="insertCar">
        insert into t_car(id, car_num, brand, guide_price, produce_time, car_type) 
        values(null, #{carNum}, #{brand}, #{guidePrice}, #{produceTime}, #{carType})
    </insert>
    
</mapper>

2.1.3 注意事項(xiàng)

  1. 鍵名匹配原則#{}中的名稱必須與Map中的key完全一致
  2. 空值處理:如果key不存在,對(duì)應(yīng)的值將為null
  3. 命名規(guī)范:建議使用有意義的key名稱,提高代碼可讀性

2.2 使用Map進(jìn)行數(shù)據(jù)查詢

@Test
public void testSelectByMap() {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("minPrice", 10.0);
    paramMap.put("brand", "寶馬");
    
    List<Map<String, Object>> result = sqlSession.selectList("selectCarByCondition", paramMap);
    
    for (Map<String, Object> car : result) {
        System.out.println(car);
    }
    
    sqlSession.close();
}

三、MyBatis中使用POJO類實(shí)現(xiàn)CRUD

3.1 POJO類定義

// Car.java
public class Car {
    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;
    
    // 構(gòu)造方法
    public Car() {}
    
    public Car(Long id, String carNum, String brand, Double guidePrice, 
               String produceTime, String carType) {
        this.id = id;
        this.carNum = carNum;
        this.brand = brand;
        this.guidePrice = guidePrice;
        this.produceTime = produceTime;
        this.carType = carType;
    }
    
    // Getter和Setter方法
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    
    public String getCarNum() { return carNum; }
    public void setCarNum(String carNum) { this.carNum = carNum; }
    
    // ... 其他getter和setter
}

3.2 使用POJO進(jìn)行數(shù)據(jù)插入

@Test
public void testInsertCarByPOJO() {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    
    // 使用POJO對(duì)象封裝數(shù)據(jù)
    Car car = new Car(null, "3333", "比亞迪秦", 30.0, "2020-11-11", "新能源");
    
    // 執(zhí)行SQL
    int count = sqlSession.insert("insertCar", car);
    System.out.println("插入記錄數(shù):" + count);
    
    sqlSession.commit();
    sqlSession.close();
}

3.3 POJO傳參原理

重要規(guī)則#{}占位符中的名稱對(duì)應(yīng)的是POJO類的getter方法名去掉"get"并將首字母小寫(xiě)后的名稱。

例如:

  • getCarNum() → #{carNum}
  • getGuidePrice() → #{guidePrice}
  • getUsername() → #{username}

3.4 使用POJO進(jìn)行數(shù)據(jù)查詢

3.4.1 查詢單個(gè)對(duì)象

<!-- 根據(jù)id查詢汽車信息 -->
<select id="selectById" resultType="com.example.pojo.Car">
    select * from t_car where id = #{id}
</select>
@Test
public void testSelectById() {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    
    // 查詢單個(gè)對(duì)象
    Car car = sqlSession.selectOne("selectById", 1);
    System.out.println(car);
    
    sqlSession.close();
}

3.4.2 查詢所有記錄

<!-- 查詢所有汽車信息 -->
<select id="selectAll" resultType="com.example.pojo.Car">
    select
        id,
        car_num as carNum,
        brand,
        guide_price as guidePrice,
        produce_time as produceTime,
        car_type as carType
    from t_car
</select>
@Test
public void testSelectAll() {
    SqlSession sqlSession = SqlSessionUtil.openSession();
    
    // 查詢所有記錄,返回List集合
    List<Car> carList = sqlSession.selectList("selectAll");
    
    for (Car car : carList) {
        System.out.println(car);
    }
    
    sqlSession.close();
}

四、解決字段名與屬性名映射問(wèn)題

4.1 問(wèn)題現(xiàn)象

當(dāng)數(shù)據(jù)庫(kù)字段名與Java類屬性名不一致時(shí),會(huì)出現(xiàn)屬性值為null的情況:

-- 數(shù)據(jù)庫(kù)表結(jié)構(gòu)
+----+----------+------------+--------------+---------------+----------+
| id | car_num  | brand      | guide_price  | produce_time  | car_type |
+----+----------+------------+--------------+---------------+----------+
|  1 | 1001     | 寶馬520Li  |       10.00  | 2020-10-11    | 燃油車   |
+----+----------+------------+--------------+---------------+----------+

-- 直接查詢會(huì)導(dǎo)致Car對(duì)象的carNum、guidePrice等屬性為null
-- 因?yàn)閿?shù)據(jù)庫(kù)字段是car_num,而Java屬性是carNum

4.2 解決方案

方案一:SQL中使用AS別名(推薦)

<select id="selectById" resultType="com.example.pojo.Car">
    select
        id,
        car_num as carNum,           -- 起別名
        brand,
        guide_price as guidePrice,   -- 起別名
        produce_time as produceTime, -- 起別名
        car_type as carType          -- 起別名
    from t_car
    where id = #{id}
</select>

方案二:配置駝峰命名自動(dòng)映射

在MyBatis配置文件中開(kāi)啟駝峰命名自動(dòng)映射:

<!-- mybatis-config.xml -->
<configuration>
    <settings>
        <!-- 開(kāi)啟駝峰命名自動(dòng)映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

開(kāi)啟后,MyBatis會(huì)自動(dòng)將下劃線命名的數(shù)據(jù)庫(kù)字段映射到駝峰命名的Java屬性:

  • car_num → carNum
  • guide_price → guidePrice
  • produce_time → produceTime

方案三:使用resultMap自定義映射

<resultMap id="carResultMap" type="com.example.pojo.Car">
    <id property="id" column="id"/>
    <result property="carNum" column="car_num"/>
    <result property="brand" column="brand"/>
    <result property="guidePrice" column="guide_price"/>
    <result property="produceTime" column="produce_time"/>
    <result property="carType" column="car_type"/>
</resultMap>

<select id="selectById" resultMap="carResultMap">
    select * from t_car where id = #{id}
</select>

五、Map與POJO對(duì)比與選擇

5.1 使用場(chǎng)景對(duì)比

特性Map集合POJO類
靈活性高,適合動(dòng)態(tài)參數(shù)低,結(jié)構(gòu)固定
類型安全低,運(yùn)行時(shí)才能發(fā)現(xiàn)錯(cuò)誤高,編譯時(shí)檢查
代碼可讀性低,需要查看Map鍵名高,屬性明確
IDE支持有限,無(wú)法自動(dòng)提示好,有代碼提示
適合場(chǎng)景臨時(shí)查詢、參數(shù)不固定業(yè)務(wù)實(shí)體、固定結(jié)構(gòu)

5.2 最佳實(shí)踐建議

業(yè)務(wù)實(shí)體操作使用POJO

  • 用戶、訂單、商品等核心業(yè)務(wù)實(shí)體
  • 需要頻繁操作和傳遞的數(shù)據(jù)
  • 有利于代碼維護(hù)和重構(gòu)

臨時(shí)查詢使用Map

  • 動(dòng)態(tài)條件查詢,參數(shù)不固定
  • 統(tǒng)計(jì)報(bào)表等臨時(shí)性數(shù)據(jù)操作
  • 快速原型開(kāi)發(fā)階段

混合使用策略

// 示例:使用Map封裝查詢條件,返回POJO列表
public List<Car> findCars(Map<String, Object> params) {
    return sqlSession.selectList("findCarsByCondition", params);
}

六、完整示例與總結(jié)

6.1 完整Mapper示例

<?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="com.example.mapper.CarMapper">
    
    <!-- 插入操作 -->
    <insert id="insertCar">
        insert into t_car(id, car_num, brand, guide_price, produce_time, car_type) 
        values(null, #{carNum}, #{brand}, #{guidePrice}, #{produceTime}, #{carType})
    </insert>
    
    <!-- 根據(jù)ID查詢 -->
    <select id="selectById" resultType="com.example.pojo.Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from t_car
        where id = #{id}
    </select>
    
    <!-- 查詢所有 -->
    <select id="selectAll" resultType="com.example.pojo.Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from t_car
    </select>
    
    <!-- 更新操作 -->
    <update id="updateCar">
        update t_car
        set car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType}
        where id = #{id}
    </update>
    
    <!-- 刪除操作 -->
    <delete id="deleteById">
        delete from t_car where id = #{id}
    </delete>
    
</mapper>

6.2 關(guān)鍵點(diǎn)總結(jié)

#{}${}的區(qū)別

  • #{}是預(yù)編譯處理,防止SQL注入
  • ${}是字符串替換,有SQL注入風(fēng)險(xiǎn)

resultType與resultMap

  • resultType:自動(dòng)映射,要求字段名與屬性名一致或配置別名
  • resultMap:自定義映射,處理復(fù)雜映射關(guān)系

占位符命名規(guī)則

  • Map傳參:#{}中寫(xiě)Map的key
  • POJO傳參:#{}中寫(xiě)getter方法對(duì)應(yīng)的屬性名

性能優(yōu)化建議

  • 盡量使用POJO,享受編譯時(shí)檢查的好處
  • 復(fù)雜查詢考慮使用resultMap提高可讀性
  • 批量操作使用批量API提高性能

通過(guò)本文的學(xué)習(xí),你應(yīng)該掌握了MyBatis中使用Map和POJO實(shí)現(xiàn)CRUD操作的核心技術(shù)。在實(shí)際開(kāi)發(fā)中,根據(jù)具體場(chǎng)景選擇合適的方式,既能提高開(kāi)發(fā)效率,又能保證代碼質(zhì)量。

以上就是MyBatis使用Map與POJO類實(shí)現(xiàn)CRUD操作的步驟詳解的詳細(xì)內(nèi)容,更多關(guān)于MyBatis Map與POJO類實(shí)現(xiàn)CRUD的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Javaweb實(shí)現(xiàn)上傳下載文件的多種方法

    Javaweb實(shí)現(xiàn)上傳下載文件的多種方法

    本篇文章主要介紹了Javaweb實(shí)現(xiàn)上傳下載文件,有多種實(shí)現(xiàn)方式,需要的朋友可以參考下。
    2016-10-10
  • Java并發(fā) 結(jié)合源碼分析AQS原理

    Java并發(fā) 結(jié)合源碼分析AQS原理

    這篇文章主要介紹了Java并發(fā) 結(jié)合源碼分析AQS原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Java中ResultSetMetaData 元數(shù)據(jù)的具體使用

    Java中ResultSetMetaData 元數(shù)據(jù)的具體使用

    本文主要介紹了Java中ResultSetMetaData 元數(shù)據(jù)的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • SpringBoot項(xiàng)目中resources文件讀取實(shí)踐

    SpringBoot項(xiàng)目中resources文件讀取實(shí)踐

    本文詳細(xì)介紹了SpringBoot項(xiàng)目中讀取resources目錄下文件的9種主流方式,并提供了一個(gè)完整的控制器Demo示例,幫助開(kāi)發(fā)者快速定位最適合的資源加載方案
    2026-01-01
  • SpringBoot接收f(shuō)orm-data和x-www-form-urlencoded數(shù)據(jù)的方法

    SpringBoot接收f(shuō)orm-data和x-www-form-urlencoded數(shù)據(jù)的方法

    form-data和x-www-form-urlencoded是兩種不同的HTTP請(qǐng)求體格式,本文主要介紹了SpringBoot接收f(shuō)orm-data和x-www-form-urlencoded數(shù)據(jù)的方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-05-05
  • Java多態(tài)概念、實(shí)現(xiàn)機(jī)制與實(shí)踐應(yīng)用詳解

    Java多態(tài)概念、實(shí)現(xiàn)機(jī)制與實(shí)踐應(yīng)用詳解

    多態(tài)是指同一個(gè)方法在不同對(duì)象上具有不同的行為,通過(guò)多態(tài)程序可以在運(yùn)行時(shí)決定調(diào)用哪個(gè)方法,從而提高代碼的靈活性和可擴(kuò)展性,這篇文章主要介紹了Java多態(tài)概念、實(shí)現(xiàn)機(jī)制與實(shí)踐應(yīng)用的相關(guān)資料,需要的朋友可以參考下
    2026-01-01
  • 淺談spring ioc的注入方式及注入不同的數(shù)據(jù)類型

    淺談spring ioc的注入方式及注入不同的數(shù)據(jù)類型

    這篇文章主要介紹了淺談spring ioc的注入方式及注入不同的數(shù)據(jù)類型,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2017-12-12
  • Java并發(fā)編程之Semaphore詳解

    Java并發(fā)編程之Semaphore詳解

    這篇文章主要介紹了Java并發(fā)編程之concurrent包中的Semaphore詳解,信號(hào)量Semaphore一般用來(lái)表示可用資源的個(gè)數(shù),相當(dāng)于一個(gè)計(jì)數(shù)器,可類比生活中停車場(chǎng)牌子上面顯示的停車場(chǎng)剩余車位數(shù)量,需要的朋友可以參考下
    2023-12-12
  • Java的validation參數(shù)校驗(yàn)代碼實(shí)例

    Java的validation參數(shù)校驗(yàn)代碼實(shí)例

    這篇文章主要介紹了Java的validation參數(shù)校驗(yàn)代碼實(shí)例,Validation參數(shù)校驗(yàn)是指在程序運(yùn)行中對(duì)傳進(jìn)來(lái)的參數(shù)進(jìn)行合法性檢查,以保證程序的正確性和安全性,需要的朋友可以參考下
    2023-10-10
  • 四個(gè)Java常見(jiàn)分布式鎖的選型和性能對(duì)比

    四個(gè)Java常見(jiàn)分布式鎖的選型和性能對(duì)比

    當(dāng)涉及到分布式系統(tǒng)中的并發(fā)控制和數(shù)據(jù)一致性時(shí),分布式鎖是一種常見(jiàn)的解決方案,本文將對(duì)幾種常見(jiàn)的分布式鎖實(shí)現(xiàn)原理、實(shí)現(xiàn)示例、應(yīng)用場(chǎng)景以及優(yōu)缺點(diǎn)進(jìn)行詳細(xì)分析,需要的可以參考一下
    2023-05-05

最新評(píng)論

临高县| 佛山市| 壶关县| 绿春县| 德安县| 全南县| 赤壁市| 和政县| 兴和县| 新闻| 朝阳区| 阳曲县| 阜平县| 甘孜| 普兰店市| 甘洛县| 邓州市| 漯河市| 会昌县| 怀柔区| 洪洞县| 田阳县| 岳西县| 元氏县| 临桂县| 沿河| 莆田市| 东乡族自治县| 公安县| 张掖市| 赤城县| 济宁市| 改则县| 邳州市| 堆龙德庆县| 太原市| 北安市| 即墨市| 高密市| 潍坊市| 遂溪县|