We have several domain objects with nullable fields. We have read that hibernate needs the 'raw' object to map it correctly, so our getters return optionals. Our domain objects look like this:
public class User {
private String firstName;
private User boss;
public Optional<String> getFirstName(){
....
}
public Optional<User> getBoss() {
...
}
}
But now we have problems resolving/binding these fields in .jspx files. (Both displaying as well as in form input fields.) For primitive types and Strings we could bypass this by defining a custom OptionalToStringConverter.
Still a problem are nullable references to other domain objects.
We considered several options but aren't really satisfied with any of them:
- Defining custom Converters for all Domain Objects and Types (Would lead to many converters and doesn't seem to work for input fields)
- Defining optional and non-optional getters on each domain object (1. duplicate code, 2.we want to indicate nullable fields cleary, 3. doesn't feel clean to access optional and non-optional fields differently)
- Defining a 'show command' that returns the 'raw' value or null (duplicate code)
- Defining custom tagx that handles optionals (when domain object becomes non-optional we would have to change the tagx)
We wondered if there is a nice and clean way to resolve optionals in jspx.
In terms of form binding, Spring handles this quite nicely: e.g. It will map the first value below to
Optional.empty(), and the second and third to the appropriateOptional<Boolean>.In terms of displaying the values, I haven't found anything better than just using
.getand.presentetc. within EL expressions. It does make for quite cumbersome code.