DEV Community

Java Records in Spring Boot Rest API

Panos Sideris on April 17, 2020

Introduction to Records Java 14 was released in March 2020 and one of the features that drew our attention was Records. Let's start by e...
Collapse
 
stoussaint profile image
Stéphane Toussaint

Thank you for this introduction !

I'm able to build the project by setting the IDE as you tell, but I can't get the projet running. Whenever I start "bootRun", I get the following exception :

LinkageError com.psideris.moviesapi.MoviesApiApplication
java.lang.UnsupportedClassVersionError: Preview features are not enabled for com/psideris/moviesapi/MoviesApiApplication (class file version 58.65535). Try running with '--enable-preview'

The --enable-preview is set for compile and test in build.gradle. Is there something else to do to run the project with this param ? I can't figure out how.

Collapse
 
tobq profile image
Tobi • Edited

Would be so much better if you didn't need the Jackson annotations (and it worked automatically like with normal classes). A lot of duplication / boilerplate

Collapse
 
psideris89 profile image
Panos Sideris

That would be nice indeed. For me it seems a fair trade, having to add annotations instead of declaring a whole class however the most significant benefit it's not the amount of code added or reduced but the immutability the Records offer.

Collapse
 
tobq profile image
Tobi • Edited

It seems like something the devs will eventually get working without annotations, as records are so new (still a preview) . Indeed, the immutability is a great bonus / pattern.

Collapse
 
stoussaint profile image
Stéphane Toussaint

Ok I get it finally. Need to add

bootRun {
    jvmArgs(['--enable-preview'])
}
Collapse
 
omrico profile image
omrico

So with older Java I'd use Lombok to eliminate the boiler plate code. I do like the option of @AllArgsConstructor and @NoArgsConstructor which is missing from this Record class.