限制JPA中集合的大小 [英] Limit the size of a collection in JPA

查看:229
本文介绍了限制JPA中集合的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个这样的实体

@Entity
Class A{
//fields

@Onetomany
Set<B> b; // 
}

现在,我如何限制集合中'B'的数量,使得当集合中有新条目时,最旧的条目将被删除,例如

Now, how do I limit the number of 'B's in the collection in such a way that, when there is a new entry in the collection, the oldest one is removed, some thing like removeEldestEntry we have in a LinkedHashMap.

我正在将MySQL 5.5 DB与Hibernate一起使用.预先感谢.

I am using MySQL 5.5 DB with Hibernate. Thanks in advance.

编辑

我的目标是在任何时间点该表中的条目数都不超过N个. 我要解决的一个方法是使用Set并安排作业以删除较旧的条目.但是我发现它很脏.我正在寻找更清洁的解决方案.

My goal is not to have more than N number of entries in that table at any point of time. One solution I have is to use a Set and schedule a job to remove the older entries. But I find it dirty. I am looking for a cleaner solution.

推荐答案

我将使用代码手动执行此规则.主要思想是应该很好地封装集合B,以使客户端只能通过公共方法(即addB())更改其内容.只需在此方法(addB())中确保该规则,即可确保集合B中的条目数不能大于一个值.

I would use the code to manually enforce this rule. The main idea is that the collection B should be well encapsulated such that client only can change its content by a public method (i.e addB()) . Simply ensure this rule inside this method (addB()) to ensure that the number of entries inside the collection B cannot larger than a value.

A:

@Entity
public class A {


    public static int MAX_NUM_B = 4;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<B> b= new LinkedHashSet<B>();

    public void addB(B b) {
        if (this.b.size() == MAX_NUM_B) {
            Iterator<B> it = this.b.iterator();
            it.next();
            it.remove();
        }
        this.b.add(b);
    }

    public Set<B> getB() {
        return Collections.unmodifiableSet(this.b);
    }
}

B:

@Entity 
public class B{

    @ManyToOne
    private A a;
}

要点:

  • A应该是关系的所有者.
  • 在A中,不要简单地返回B,因为客户端可以绕过addB(B b)中实现的检查逻辑并自由更改其内容,而是返回B的不可修改视图.
  • 在@OneToMany中,将orphanRemoval设置为true,以告诉JPA在从B集合中删除B的相应实例之后,删除B的DB记录.
  • A should be the owner of the relationship.
  • In A , do not simply return B as client can bypass the checking logic implemented in addB(B b) and change its content freely.Instead , return an unmodifiable view of B .
  • In @OneToMany , set orphanRemovalto true to tell JPA to remove the B 's DB records after its corresponding instances are removed from the B collection.

这篇关于限制JPA中集合的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆