java - Hibernate - Either field A OR B can be null but one of A or B must not be null -
is possible in hibernate model use case in have 2 fields , either of them null @ least 1 of them must not null? below code have @ moment don't fact have set both of them @column(nullable = true). in case want either personal email address or work address. there way support this? or alternative approach needed?
public class applicantdetails { //... @onetoone(optional = false) private contactdetails contactdetails; //... } public class contactdetails { @id @generatedvalue(strategy = generationtype.auto) private integer id; /*need @ least 1 email address doesn't matter one.*/ @column(nullable = true, unique = true) private string personalemail; @column(nullable = true, unique = true) private string workemail; //... }
i recommend anyway define check constraint in database if database supports form of it:
check (personal_email not null or work_email not null) regarding middle layer, can write own validators in services store/update contactdetails , raise corresponding exceptions if attempts store/update inconsistent state made, or can use validation framework hibernate validator.
a quick workaround utilise entity lifecycle callback methods:
@prepersist @preupdate private void validate() { if (personalemail == null && workemail == null) { throw new validationexception(); } }
Comments
Post a Comment