0

With an @Entity class containing a field:

@JsonProperty("arrays")
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "systemID", nullable = true)
private List<PVArray> arrays = null;

That defines a collection. The next step is to enforce that arrays must have one or more entries.

The system is being developed with Spring Boot, using Jackson for JSON serializing/deserializing, and Hibernate and JPA for persistence.

I think a constraint like this has to be enforced manually. I haven't found any annotation describing this constraint. Manual enforcement in the setter doesn't seem sufficient - what if the incoming JSON simply does not have an arrays field? The setter would never be called and no chance for enforcement.

Is it possible to write a method that's called after the JSON is deserialized? Or more generally (because obviously the classes are instantiated other ways besides deserializing JSON), a method that's called at the end of instantiating the object, so that object constraints can be enforced?

I have other constraints to consider than just the size of certain collections. For example one class can have only one of its fields set, not both.

David Herron
  • 898
  • 2
  • 12
  • 22
  • 1
    https://docs.oracle.com/javaee/7/api/javax/validation/constraints/Size.html – JB Nizet Sep 25 '17 at 19:18
  • This is not jpa, which simply persists what you have. Java bean validation api is what you need. Update the question and tags –  Sep 26 '17 at 04:53
  • Thank you for the pointer -- yet another kitchen sink to learn. I'll be able to try @Size in a couple days. – David Herron Sep 26 '17 at 05:39

1 Answers1

2

you can do something like this:

@Size(min=1, max=10)
@JsonProperty("arrays")
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "systemID", nullable = true)
private List<PVArray> arrays;

With size you are saying that at least you need from 1 to 10 elements

nole
  • 1,422
  • 4
  • 20
  • 32