Question

I have an entity which is an AccessCard and I want to have a boolean field "active". So for example multiple people may have had the AccessCard, but it is only active on the current holder. The current holder will have the active field = true and all the previous holders will have the active field = false.

Obviously I could just handle this on the interface side, and not allow to activate a card before de-activation, but I would also like this contraint in the Database.

Any ideas how I should annotate the "active" column?

Was it helpful?

Solution 2

Instead of a boolean why not add a (possibly another, since you seem to track everyone who had a key) @ManyToOne reference to your person entity to the AccessCard Entity? Like this:

public class AccessCard {

    @ManyToOne(Cascade = CascadeType.PERSIST | CascadeType.MERGE)
    @JoinColumn(referencedColumnName="person_id")
    private Person cardHolder;

    public getCardHolder() {
        return cardHolder;
    }
}   


public class Person {

    @OneToMany(Cascade = CascadeType.PERSIST | CascadeType.MERGE)
    private Set posessingCards;
}
  • Now you can check if a specific card is in use by checking for null on the return of getCardHolder. Or you could just add another method the does the check and returns a boolean instead.
  • This would ensure that transferring the card to a new person removes it from the current one and a check to see if it's active would just be a check for null instead.
  • Activation/Deactivation would effectively be handled by assigning the key to a person, two birds with one stone, you know if it's active AND who has it.

OTHER TIPS

Which RDBMS you're using? In Oracle you could do some thing like in accepted answer HERE.

I don't think there is JPA annotation that allows creating constraints based on field value. There is @UniqueConstraint that allows creating constraints on fields list, but it still does not take under consideration field value (because you want to have only one record with active=true for AccessCard, but many with active=false).

What you could do is to create private getter to get access cards assignments and create public transient method for returning active card assignment. When first time called,it would iterate all assignments, pick up active one and assign to property so that you don't have to iterate through all assignemnts everytime getActiveAssignment is called. On setter for active assignment you could set active to false for all assignments and then set true for expected one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top