Difference between revisions of "JSF Hibernate - Implement checks (check constraints) on a certain column"

(Created page with "If you want to allow only certain values in a column field, then you can do that directly on the database level of your Java web app. Go to your "entity" class and add the fo...")
 
(No difference)

Latest revision as of 10:09, 2 August 2020

If you want to allow only certain values in a column field, then you can do that directly on the database level of your Java web app.

Go to your "entity" class and add the following as an annotation.

@Check(constraints="scala IN (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)")

"scala" is here the name of the column that should be checked. You have to use the column name that will be used on your database. You have to use that name, if you did define the column name of your database table with the annotation "@Column(name="columnname")".

The check annotation is part of the class "org.hibernate.annotations.Check".

Full example:

@Entity
@SequenceGenerator(name = "decisioncriteria_seq", sequenceName = "decisioncriteria_id_seq", allocationSize = 1)
@Check(constraints="scala IN (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)")
public class DecisionCriteria implements Serializable {

    @GeneratedValue(strategy = GenerationType.AUTO, generator = "decisioncriteria_seq")
    @Id
    private Integer decisionCriteria_id;
    @Column(nullable = false)
    private String title;
    private Integer scala;
[...]
}