1

I have Consumer table in database where I have check constraint on consumer_type column like below:

ALTER TABLE consumer
    ADD CONSTRAINT Check_consumer_consumer_type CHECK (consumer_type IN ('ACCOUNT','ORGANIZATION'))

Now from hibernate side I want to add check constraint annotation which will allow only "ACCOUNT" and "ORGANIZATION" value in consumer type table.

Which hibernate / jpa annotation I should use for this purpose?

0

1 Answer 1

6

Assuming that you have the consumer type represented using String in your entity you could easily replace it with an enum and Java's type safety would ensure that you will not be able to pass anything else to it.

Using EnumType.STRING, the values will be stored as Strings in your database (and mapped back to enum when you load the entity), so no change to your data would be required.


Example

@Entity
public class Consumer {

    public static enum ConsumerType {
        ACCOUNT, ORGANIZATION
    }

    @Enumerated(EnumType.STRING)
    @Column(name="consumer_type", nullable=false)
    private ConsumerType consumerType;

    // Other properties, getters/setters, ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.