簡體   English   中英

關系n:3休眠

[英]Relationship n:3 Hibernate


我想知道如何在Hibernate上建立an:3關系模型。 我看過很多使用注解@ ManyToMany,@ OneToMany ..等的示例,但是沒有一個是n:x,xa自然數。
你能給我一個簡單的例子嗎? 提前致謝

您可以使用驗證器。 我認為您的要求不能被視為數據庫設計問題,而應被視為驗證問題。 改用驗證器。 您可以編寫自定義Bean驗證器(JSR-303),以驗證列表中元素的數量:

public class MyListSizeValidator implements
        ConstraintValidator<MyListConstraintAnnotation, List<?> /* list of any type */ > {

    public void initialize(MyListConstraintAnnotation myannotation) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public boolean isValid(List<?> mylist, ConstraintValidatorContext constraintValidatorContext) {
        return mylist.size() < 4;
    }
}

@Documented
@Constraint(validatedBy = MyListSizeValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyListConstraintAnnotation {
    String message() default "List is full!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

用法如下:

class MyCronBean {
    @NotNull
    @MyListConstraintAnnotation
    private List<MyObject> list;
    /** setters and getters */
}

更新:您可以在Maven中為JSR-303實現“休眠驗證器”使用:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.0.2.GA</version>
</dependency>

如果您不談論三元關聯 (m:n:1),則需要使用@ManyToMany。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM