ModelMapper基本使用和常見場(chǎng)景示例詳解
ModelMapper 是一個(gè)用于簡(jiǎn)化 Java 對(duì)象之間屬性映射的庫(kù),它能夠自動(dòng)或通過自定義規(guī)則將一個(gè)對(duì)象的屬性值映射到另一個(gè)對(duì)象中。以下是 ModelMapper 的基本使用方法和常見場(chǎng)景示例:
1. 添加依賴
首先,需要在項(xiàng)目中添加 ModelMapper 的依賴。如果你使用 Maven,可以在 pom.xml 中添加以下依賴:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.1</version> <!-- 使用最新版本 -->
</dependency>2. 基本用法
ModelMapper 的核心是 ModelMapper 類,通過它的 map 方法可以實(shí)現(xiàn)對(duì)象之間的屬性映射。
示例:簡(jiǎn)單對(duì)象映射
假設(shè)有兩個(gè)類 Source 和 Destination,它們的屬性名相同:
import org.modelmapper.ModelMapper;
class Source {
private String name;
private int age;
// getters and setters
}
class Destination {
private String name;
private int age;
// getters and setters
}
public class Main {
public static void main(String[] args) {
ModelMapper modelMapper = new ModelMapper();
Source source = new Source();
source.setName("Alice");
source.setAge(25);
// 將 Source 對(duì)象映射到 Destination 對(duì)象
Destination destination = modelMapper.map(source, Destination.class);
System.out.println(destination.getName()); // 輸出: Alice
System.out.println(destination.getAge()); // 輸出: 25
}
}3. 自定義映射規(guī)則
如果源對(duì)象和目標(biāo)對(duì)象的屬性名不同,或者需要更復(fù)雜的映射邏輯,可以通過以下方式自定義:
方式 1:使用 PropertyMap
import org.modelmapper.PropertyMap;
ModelMapper modelMapper = new ModelMapper();
// 自定義映射規(guī)則
modelMapper.addMappings(new PropertyMap<Source, Destination>() {
@Override
protected void configure() {
map().setUserName(source.getName()); // 將 Source 的 name 映射到 Destination 的 userName
map().setYears(source.getAge()); // 將 Source 的 age 映射到 Destination 的 years
}
});
Source source = new Source();
source.setName("Bob");
source.setAge(30);
Destination destination = modelMapper.map(source, Destination.class);
System.out.println(destination.getUserName()); // 輸出: Bob
System.out.println(destination.getYears()); // 輸出: 30方式 2:使用 Lambda 表達(dá)式(ModelMapper 2.3.0+)
ModelMapper modelMapper = new ModelMapper();
// 使用 Lambda 表達(dá)式自定義映射
modelMapper.typeMap(Source.class, Destination.class)
.addMappings(mapper -> mapper.map(src -> src.getName(), Destination::setUserName))
.addMappings(mapper -> mapper.map(src -> src.getAge(), Destination::setYears));
Destination destination = modelMapper.map(source, Destination.class);4. 集合映射
ModelMapper 也支持集合類型的映射,例如將 List<Source> 映射為 List<Destination>:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<Source> sources = Arrays.asList(
new Source("Alice", 25),
new Source("Bob", 30)
);
// 方法 1:使用 Stream 和 map
List<Destination> destinations = sources.stream()
.map(source -> modelMapper.map(source, Destination.class))
.collect(Collectors.toList());
// 方法 2:直接映射集合(ModelMapper 2.3.0+)
List<Destination> destinations2 = modelMapper.map(sources, new TypeToken<List<Destination>>() {}.getType());5. 高級(jí)配置
匹配策略
ModelMapper 提供了多種匹配策略,例如:
STRICT:嚴(yán)格匹配(默認(rèn)),屬性名和類型必須完全一致。LOOSE:寬松匹配,屬性名可以部分匹配。STANDARD:標(biāo)準(zhǔn)匹配,支持駝峰命名轉(zhuǎn)換。
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE); // 使用寬松匹配忽略某些屬性
modelMapper.typeMap(Source.class, Destination.class)
.addMappings(mapper -> mapper.skip(Destination::setAge)); // 忽略 age 屬性的映射自定義轉(zhuǎn)換器
如果需要將屬性值進(jìn)行轉(zhuǎn)換(例如日期格式化),可以使用 Converter:
import org.modelmapper.Converter;
import org.modelmapper.spi.MappingContext;
Converter<String, Date> stringToDateConverter = ctx -> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(ctx.getSource());
} catch (ParseException e) {
throw new RuntimeException(e);
}
};
modelMapper.addConverter(stringToDateConverter);6. 在 Spring Boot 中使用
在 Spring Boot 項(xiàng)目中,可以將 ModelMapper 配置為 Bean:
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}然后在 Service 或 Controller 中注入使用:
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private ModelMapper modelMapper;
public Destination convertToDestination(Source source) {
return modelMapper.map(source, Destination.class);
}
}總結(jié)
ModelMapper 的核心功能包括:
- 自動(dòng)映射:根據(jù)屬性名和類型自動(dòng)映射。
- 自定義映射:通過
PropertyMap或 Lambda 表達(dá)式自定義映射規(guī)則。 - 集合映射:支持
List、Set等集合類型的映射。 - 高級(jí)配置:支持匹配策略、忽略屬性、自定義轉(zhuǎn)換器等。
- Spring 集成:可以輕松集成到 Spring Boot 項(xiàng)目中。
通過 ModelMapper,可以大大減少對(duì)象映射的樣板代碼,提高開發(fā)效率。
到此這篇關(guān)于ModelMapper基本使用和常見場(chǎng)景示例詳解的文章就介紹到這了,更多相關(guān)ModelMapper使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java通俗易懂系列設(shè)計(jì)模式之責(zé)任鏈模式
這篇文章主要介紹了Java通俗易懂系列設(shè)計(jì)模式之責(zé)任鏈模式,對(duì)設(shè)計(jì)模式感興趣的同學(xué),一定要看一下2021-04-04
MyBatis使用CASE WHEN進(jìn)行批量更新的高效寫法
當(dāng)我們使用mybatis的時(shí)候,可能經(jīng)常會(huì)碰到一批數(shù)據(jù)的批量更新問題,因?yàn)槿绻粭l數(shù)據(jù)一更新,那每一條數(shù)據(jù)就需要涉及到一次數(shù)據(jù)庫(kù)的操作,包括網(wǎng)絡(luò)IO以及磁盤IO,可想而知,這個(gè)效率是非常低下的,那么今天我們就來(lái)總結(jié)一下,如何使用mybatis做批量更新,需要的朋友可以參考下2025-10-10
Flyway詳解及Springboot集成Flyway的詳細(xì)教程
Flayway是一款數(shù)據(jù)庫(kù)版本控制管理工具,,支持?jǐn)?shù)據(jù)庫(kù)版本自動(dòng)升級(jí),Migrations可以寫成sql腳本,也可以寫在java代碼里。這篇文章主要介紹了Flyway詳解及Springboot集成Flyway的詳細(xì)教程的相關(guān)資料,需要的朋友可以參考下2020-07-07
Java中的數(shù)組基礎(chǔ)知識(shí)學(xué)習(xí)教程
這篇文章主要介紹了Java中的數(shù)組基礎(chǔ)知識(shí)學(xué)習(xí)教程,文中同時(shí)也整理了Java對(duì)數(shù)字類型的支持狀況及Number類中的方法,需要的朋友可以參考下2016-02-02
Mybatis-plus多數(shù)據(jù)源配置的兩種方式總結(jié)
這篇文章主要為大家詳細(xì)介紹了Mybatis-plus中多數(shù)據(jù)源配置的兩種方式,文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起了解一下2022-10-10
Mybatis pagehelper分頁(yè)插件使用過程解析
這篇文章主要介紹了mybatis pagehelper分頁(yè)插件使用過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
Java Web學(xué)習(xí)之MySQL在項(xiàng)目中的使用方法
mysql數(shù)據(jù)庫(kù)是我們?cè)谌粘i_發(fā)中經(jīng)常會(huì)用到的,下面這篇文章主要給大家介紹了關(guān)于Java Web學(xué)習(xí)之MySQL在項(xiàng)目中的使用方法,需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04
Java中前臺(tái)往后臺(tái)傳遞多個(gè)id參數(shù)的實(shí)例
下面小編就為大家?guī)?lái)一篇Java中前臺(tái)往后臺(tái)傳遞多個(gè)id參數(shù)的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2017-07-07

