I'm searching for a Java library that can automatically generate a Data Transfer Object (DTO) from an existing business class, specifically for data transmission purposes. For example, I have a class called Trade with some fields that might not follow the camelCase convention or could be misnamed. I'd like the generated DTO, TradeDTO, to have correctly named fields with minimal manual adjustments. Ideally, the library would allow me to provide some simple annotations or instructions during compile time, so that as the original Trade class evolves, the TradeDTO updates as well without requiring further changes. I've tried using MapStruct, but it only facilitates copying between POJOs rather than generating new classes from existing ones.
5 Answers
Instead of creating DTOs traditionally, why not write an OpenAPI specification? You can generate the DTOs from that and then use MapStruct for mapping. Just make sure to adjust its reporting level to ERROR to get everything included in the mapper!
A practical approach could be to use records for your DTOs. They're much less verbose and inherently immutable, which can reduce boilerplate code significantly. This could be a neat workaround for your situation!
I suggest looking into using Protobuf if you're not already, as it can simplify creating DTOs. Also, if your business class closely resembles your DTOs, you could potentially reuse the business class directly for your API, eliminating the need for complicated DTOs altogether.
I haven’t found a perfect solution for your situation, but many developers use tools like Immutables, Lombok, or even Protobuf to help create both business and DTO classes. Then, you can leverage MapStruct with a protobuf SPI for mapping between them. Alternatively, using Jackson annotations on your business class can help with JSON mapping, but it's not the same as auto-generating DTOs directly. You could suggest a feature request to MapStruct for generating POJOs if that’s something that interests you.
Honestly, given your needs, it seems simple enough to create your own annotation processor for this. Check out the article on Java Annotation Processing Builder for some ideas. Writing your custom processor allows you to tailor the DTO generation exactly how you want it!
Yeah, it's a good starter project to get into code generation! Consider using Velocity templates instead of plain string manipulation; the syntax highlighting and autocomplete will really help in the long run.
Great point! If you need a reference for this, you might want to look at [magic-bean](http://github.com/bowbahdoe/magic-bean). It’s a solid example.