【问题标题】:Hibernate enforcing relation with "central" entity休眠执行与“中心”实体的关系
【发布时间】:2014-04-25 13:15:03
【问题描述】:

假设我有以下实体关系:

  • 一个人有很多宠物

  • 一个人有很多玩具

  • 一只宠物有很多玩具

人物 1 ----> * 宠物

人物 1 ----> * 玩具

宠物 * ----> * 玩具

我想强制执行以下事实:一只宠物只能从拥有他的人那里获得玩具。我不知道是否可以在数据库级别做到这一点。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    您可以尝试创建自定义检查约束,下面的链接将帮助您这样做:-

    http://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html_single/#validator-customconstraints

    ConstraintValidatorisValid() 方法中,您可以获取人员的 toyIds 列表并根据您的 toyId 输入列表验证它们

    public class ValueValidator implements ConstraintValidator<CheckCase, String> {
    
    private ValueMode valueMode;
    
    public void initialize(CheckCase constraintAnnotation) {
        this.valueMode= constraintAnnotation.value();
    }
    
    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
    
      // You can have your logic here and can validate the same.
       // Here you can fetch the ToyIds and validate the same from below list of ToyIds
    //select p.toyID from Person p join Toy t where p.toyID = t.toyId and p.petId in (Input list of toyids)
    }
    

    【讨论】:

    • 谢谢,但我想知道是否可以在数据库级别创建这样的约束。
    猜你喜欢
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    相关资源
    最近更新 更多