3

My Spring-Boot & Couchbase app has a Cat object in the DB.

In a new app version, we added new boolean field to out Cat document object:

@RequiredArgsConstructor
@AllArgsConstructor(onConstructor = @__(@PersistenceConstructor))
@Document
@Data
@Builder
@EqualsAndHashCode
public class Cat {
....
@Field
final boolean isHungry

But now, we already have Cat objects that are in the DB and don't have this field.

When the app is trying to read these Cats we get this error:

org.springframework.data.mapping.model.MappingInstantiationException: Failed 
  to instantiate com.example.Cat using constructor public 
  com.example.Cat(...) with arguments ... 
...
Caused by: java.lang.IllegalArgumentException: Parameter isHungry must not be null!

Isn't there a way to tell Spring that if the field is missing in the DB, it should use a default value (false in this case)

riorio
  • 6,500
  • 7
  • 47
  • 100

2 Answers2

1

Try making a constructor with all parameters except isHungry, and set isHungry to false

aBnormaLz
  • 809
  • 6
  • 22
  • The potential problem I see with the "add another constructor" way, is that if in the future more fields will be added to the `Cat`, we will need to have many constructors with different combinations (E.g. without `isHungry`, without `isHungry` & `favoriteToy`....) – riorio Dec 16 '18 at 06:33
1

How about changing isHungry to Boolean and adding a getter, which will map null to false?

Mafor
  • 9,668
  • 2
  • 21
  • 36