With Java record
being immutable, I don't know how to use them properly in the context of something like a CRUD application.
If we take a very simple example of a "Organization" record
:
public record Organization(String id, String name){}
This looks good, its immutable and has all the good stuff built into it.
Now, let's say I want to update the name
value, I have been doing the following:
public record Organization(@Id String id, String name){
public static Organization withNewName(
final String name,
Organization organization
) {
return new Organization(organization.id, name);
}
}
This is okay, I create a new record
with the updated name that I want. I can use this elsewhere in my code:
Organization renamedOrganization = Organization.withNewName("Fancy company", organization);
But this gets out of hand as soon as we have a real world example where the record
might have 10, or even 100 different properties. Things get even more crazy as records don't have default values, so when dealing with Lists which are null at initialization.
I've used MapStruct for handling the basic remapping but even this seems like an overkill.
What is the proper design pattern here for working with immutable objects, when they need to be updated so they can be pushed into a databases should I have just stuck with classes and Lombok for database entities?