Hibernate @Check annotation not working at the field level

Viewed 768

constraint listI used @Check annotation at the field level, but hibernate not creates check constraints on the database. I researched that this is a bug, and @Check annotation can only be used once and at the class level. Ok, but how can I add multiple constraints at the class level? I don't want to add all conditions to the same constraint.

@Entity
public class TemplateTest{

    @Id
    private String id;

    @Column(length = 20, nullable = false)
    private String name;

    @Column(precision = 5, scale = 2, nullable = false)
    @Check(constraints = "AMOUNT > 0")
    private BigDecimal amount;

    @Column(nullable = false)
    @Check(constraints = "DISPLAY_ORDER > 0")
    private int displayOrder;

}

vs

@Entity
@Check(constraints = "DISPLAY_ORDER > 0 and AMOUNT > 0")
public class TemplateTest{

    @Id
    private String id;

    @Column(length = 20, nullable = false)
    private String name;

    @Column(precision = 5, scale = 2, nullable = false)
    private BigDecimal amount;

    @Column(nullable = false)
    private int displayOrder;

}
1 Answers
  1. You can use the columnDefinition property of @Column annotation:
@Entity
public class TemplateTest{

    @Id
    private String id;

    @Column(length = 20, nullable = false)
    private String name;

    @Column(precision = 5, scale = 2, nullable = false, columnDefinition = "bigint check(AMOUNT > 0)")
    private BigDecimal amount;

    @Column(nullable = false, columnDefinition = "bigint check(DISPLAY_ORDER > 0)")
    private int displayOrder;
}
  1. As an alternative, you can use an importing script file for adding additional constraints.

To customize the schema generation process, the hibernate.hbm2ddl.import_files configuration property must be used to provide other scripts files that Hibernate can use when the SessionFactory is started.

<property name="hibernate.hbm2ddl.import_files" value="schema-generation.sql" />

Hibernate is going to execute the script file after the schema is automatically generated.

Related