8

We are using spring-boot. I want to add conditional based constraint in java class. For e.g.

@Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "user_id")
    private Integer userId;
    @Column(name = "firstName")
    private String firstName;
    @Column(name = "lastName")
    private String lastName;
}

Now in above code I want to put @NotNull constraint on lastName property if and only if the firstName property is not empty.

Patrick
  • 12,336
  • 15
  • 73
  • 115
parthivrshah
  • 634
  • 2
  • 7
  • 14
  • 1
    At which point do you want the validation? saving the entity or at the point by populating the object? – Patrick Mar 30 '18 at 07:30
  • 1
    have a look at https://stackoverflow.com/questions/2781771/how-can-i-validate-two-or-more-fields-in-combination, sinc your constraint is a constraint over 2 fields – Turo Mar 30 '18 at 07:36
  • @Patrick, I want the validation before saving the entity. And it is at the controller layer as I am using javax validation. – parthivrshah Mar 30 '18 at 10:19
  • @parthivrshah A little late to the party, but you could instantiate the validator manually and then execute the validate method. Like `validator.validate(payload);` – alexander Aug 22 '22 at 12:07

0 Answers0