java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > ModelMapper使用

ModelMapper基本使用和常见场景示例详解

作者:有梦想的攻城狮

ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板代码,提升开发效率,本文给大家介绍ModelMapper基本使用和常见场景,感兴趣的朋友一起看看吧

ModelMapper 是一个用于简化 Java 对象之间属性映射的库,它能够自动或通过自定义规则将一个对象的属性值映射到另一个对象中。以下是 ModelMapper 的基本使用方法和常见场景示例:

1. 添加依赖

首先,需要在项目中添加 ModelMapper 的依赖。如果你使用 Maven,可以在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>3.1.1</version> <!-- 使用最新版本 -->
</dependency>

2. 基本用法

ModelMapper 的核心是 ModelMapper 类,通过它的 map 方法可以实现对象之间的属性映射。

示例:简单对象映射

假设有两个类 SourceDestination,它们的属性名相同:

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 对象映射到 Destination 对象
        Destination destination = modelMapper.map(source, Destination.class);
        System.out.println(destination.getName()); // 输出: Alice
        System.out.println(destination.getAge());  // 输出: 25
    }
}

3. 自定义映射规则

如果源对象和目标对象的属性名不同,或者需要更复杂的映射逻辑,可以通过以下方式自定义:

方式 1:使用 PropertyMap

import org.modelmapper.PropertyMap;
ModelMapper modelMapper = new ModelMapper();
// 自定义映射规则
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 表达式(ModelMapper 2.3.0+)

ModelMapper modelMapper = new ModelMapper();
// 使用 Lambda 表达式自定义映射
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. 高级配置

匹配策略

ModelMapper 提供了多种匹配策略,例如:

modelMapper.getConfiguration()
    .setMatchingStrategy(MatchingStrategies.LOOSE); // 使用宽松匹配

忽略某些属性

modelMapper.typeMap(Source.class, Destination.class)
    .addMappings(mapper -> mapper.skip(Destination::setAge)); // 忽略 age 属性的映射

自定义转换器

如果需要将属性值进行转换(例如日期格式化),可以使用 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 项目中,可以将 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);
    }
}

总结

ModelMapper 的核心功能包括:

  1. 自动映射:根据属性名和类型自动映射。
  2. 自定义映射:通过 PropertyMap 或 Lambda 表达式自定义映射规则。
  3. 集合映射:支持 ListSet 等集合类型的映射。
  4. 高级配置:支持匹配策略、忽略属性、自定义转换器等。
  5. Spring 集成:可以轻松集成到 Spring Boot 项目中。

通过 ModelMapper,可以大大减少对象映射的样板代码,提高开发效率。

到此这篇关于ModelMapper基本使用和常见场景示例详解的文章就介绍到这了,更多相关ModelMapper使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文