惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
I
InfoQ
U
Unit 42
WordPress大学
WordPress大学
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
月光博客
月光博客
D
Docker
Stack Overflow Blog
Stack Overflow Blog
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
博客园 - 聂微东
A
About on SuperTechFans
腾讯CDC
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
博客园 - 【当耐特】
罗磊的独立博客
博客园 - 三生石上(FineUI控件)
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Java Records Deserve a Mapper Built for Them
Dinuka Karun · 2026-05-24 · via DEV Community

Java Records have been stable since Java 16, and with Java 21 now the LTS baseline, they're showing up everywhere - DTOs, value objects, domain models. Immutable by design, concise, and semantically clear.

But here's the gap nobody talks about: every object mapper in the Java ecosystem was built before Records existed. They were designed around JavaBeans - mutable objects with getters, setters, and no-arg constructors. Records have none of that. So what happens? These libraries bolt on partial Record support as an afterthought, and the seams show.

I built Immuto to fill that gap.


The problem with retrofitted Record support

A Record's identity is its canonical constructor:

public record PersonDTO(Long id, String fullName, String email) {}

Enter fullscreen mode Exit fullscreen mode

That constructor is the only way to create a PersonDTO. There are no setters. There is no builder unless you write one yourself. The component accessors are read-only.

Existing mappers were not designed with this in mind. To work with Records, they either:

  • Generate setter calls that don't exist (and fail at runtime)
  • Require you to write a mutable builder as a workaround
  • Fall back to reflection on private fields — bypassing the canonical constructor entirely

These are runtime failures. You don't know something is wrong until you run the code.


What Immuto does differently

Immuto is an annotation processor - it runs during mvn compile, the same way Lombok and the APT-based approach work. It generates plain .java source files that call your record's canonical constructor directly. No reflection. No setters. No runtime surprises.

@RecordMapper
public interface PersonMapper {

    @Mapping(target = "fullName",
             expression = "java(source.firstName() + \" \" + source.lastName())")
    PersonDTO toDto(PersonEntity source);

    @InheritInverseConfiguration(name = "toDto")
    PersonEntity toEntity(PersonDTO source);
}

Enter fullscreen mode Exit fullscreen mode

After mvn compile, Immuto writes PersonMapperImpl.java into target/generated-sources. It looks exactly like code you'd write by hand:

@Generated("io.github.karunarathnad.immuto.processor.RecordMapperProcessor")
public final class PersonMapperImpl implements PersonMapper, ImmutoMapper {

    @Override
    public PersonDTO toDto(PersonEntity source) {
        if (source == null) return null;
        return new PersonDTO(
            source.id(),
            source.firstName() + " " + source.lastName(),
            source.email()
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Canonical constructor. Always. That's the contract Immuto enforces.


Compile-time validation

If a record component can't be mapped, the build fails — not at runtime, not in a test, but during compilation.

  • Unmapped component → build error
  • Type mismatch with no registered converter → build error
  • @RecordMapper on a class instead of an interface → build error

This is the behaviour Records deserve. They were designed to be explicit and safe; your mapper should be too.


Key features

Nested records — mapped recursively by matching component names. Use @Mapping(expression=...) for asymmetric nesting.

Bidirectional mapping via @InheritInverseConfiguration — define toDto, get toEntity for free.

@NullSafe — wraps the result in Optional.ofNullable(...) at the call site:

@NullSafe
Optional<AddressDTO> toAddressDto(AddressEntity entity);

Enter fullscreen mode Exit fullscreen mode

Sealed class support - Immuto understands sealed hierarchies, something no existing mapper handles.

Lifecycle hooks - @BeforeMapping and @AfterMapping methods are inlined into the generated code. No AOP, no proxy.

Custom type converters:

@Named("isoDate")
public class IsoDateConverter implements TypeConverter<LocalDate, String> {
    @Override
    public String convert(LocalDate source, MappingContext ctx) {
        return source == null ? null : source.toString();
    }
}

Enter fullscreen mode Exit fullscreen mode

Fluent runtime API - for tests or dynamic environments where APT isn't available:

FluentMapper<PersonEntity, PersonDTO> mapper = FluentMapper
    .from(PersonEntity.class)
    .to(PersonDTO.class)
    .override("fullName", p -> p.firstName() + " " + p.lastName())
    .build();

Enter fullscreen mode Exit fullscreen mode

Note: FluentMapper does use reflection — it's the explicit opt-in escape hatch, not the default path.


Getting started

<dependency>
    <groupId>io.github.karunarathnad</groupId>
    <artifactId>immuto-annotations</artifactId>
    <version>1.1.0</version>
</dependency>

<dependency>
    <groupId>io.github.karunarathnad</groupId>
    <artifactId>immuto-core</artifactId>
    <version>1.1.0</version>
</dependency>

<dependency>
    <groupId>io.github.karunarathnad</groupId>
    <artifactId>immuto-processor</artifactId>
    <version>1.1.0</version>
    <scope>provided</scope>
</dependency>

Enter fullscreen mode Exit fullscreen mode

Add the processor path to the compiler plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>io.github.karunarathnad</groupId>
                <artifactId>immuto-processor</artifactId>
                <version>1.1.0</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Enter fullscreen mode Exit fullscreen mode

Then annotate an interface, run mvn compile, and use it:

PersonMapper mapper = Immuto.getMapper(PersonMapper.class);
PersonDTO dto = mapper.toDto(entity);

Enter fullscreen mode Exit fullscreen mode


Why now

Java 21 is the current LTS. Records are not experimental — they're the idiomatic way to model immutable data in modern Java. As more codebases adopt them, the need for tooling that treats them as first-class citizens (not an edge case) grows with it.

Immuto is on Maven Central, Apache 2.0 licensed, and under active development.

GitHub: github.com/karunarathnad/immuto

Feedback, issues, and contributions are very welcome.