簡體   English   中英

@ElementCollection 至少包含一個元素,最多包含 N 個元素

[英]@ElementCollection to contain at least one element and at most N elements

有沒有辦法為@ElementCollection引用的實體應用引用計數約束?

簡化示例:

public enum Key {
    A, S, D;
};

@Entity
public class Keyboard {
     @Id
     Long id;

     // require at least one key?
     // require at most N keys?
     @ElementCollection(targetClass = Key.class)
     @JoinTable(name = "keyboard_key", joinColumns = @JoinColumn(name = "keyboard_id"))
     @Column(name = "key", nullable = false)
     @Enumerated(EnumType.STRING)
     Set<Key> keys; 
} 

Keyboard必須至少有1 Key 最多有N Key也很好。

考慮KeyboardRepository

public interface KeyboardRepository extends JpaRepository<Keyboard, Long> {}

//...
@Autowired
KeyboardRepository repo;

//..
repo.save(new Keyboard(/*id*/null, /*keys*/null); // should throw due to no-keys
repo.save(new Keyboard(/*id*/null, /*keys*/Sets.newSet()); // should throw due to no-keys
repo.save(new Keyboard(/*id*/null, /*keys*/Sets.newSet(Key.A, Key.S, Key.D)); // should throw due to eg. at most 2 keys

嘗試像這樣使用javax.validation.constraints.Size注釋:

@ElementCollection(targetClass = Key.class)
     @JoinTable(name = "keyboard_key", joinColumns = @JoinColumn(name = "keyboard_id"))
     @Column(name = "key", nullable = false)
     @Enumerated(EnumType.STRING)
     @Size(min = 1, max = N)
     Set<Key> keys; 

有關更多詳細信息,請查看如何在 spring-boot https://www.baeldung.com/javax-validation中使用 java bean 驗證

暫無
暫無

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

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