Java 限制Hibernate中成员集合的大小
我有一个问题,因为我不知道是否有可能限制活动列表的大小 我只想检索最近的5项活动。是否可以在从数据库获取数据的过程中自动执行此操作?(这样我就不必在Java中手动限制集合)Java 限制Hibernate中成员集合的大小,java,database,hibernate,Java,Database,Hibernate,我有一个问题,因为我不知道是否有可能限制活动列表的大小 我只想检索最近的5项活动。是否可以在从数据库获取数据的过程中自动执行此操作?(这样我就不必在Java中手动限制集合) @实体 公共阶层人士{ @身份证 @生成值 私人长id; @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER) @OrderBy(“时间戳描述”) @JoinColumn(name=“PERSON\u ID”) 私人名单活动; //其他二传手、接球手等。 } 基
@实体
公共阶层人士{
@身份证
@生成值
私人长id;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@OrderBy(“时间戳描述”)
@JoinColumn(name=“PERSON\u ID”)
私人名单活动;
//其他二传手、接球手等。
}
基本上,我希望在活动条目中保留20个条目(插入较新的行时删除最旧的行),但只获取5个最新的行
这可能吗?我会使用代码手动执行此规则。其主要思想是集合B应该被很好地封装,以便客户端只能通过公共方法(即addB())更改其内容。只需在此方法(addB())中确保此规则,以确保集合B中的条目数不能大于某个值
@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);
}
}
@Entity
public class B{
@ManyToOne
private A a;
}
另一个解决方案可能是
否决票
我想你得手工做
想到的一个解决方案是在实体A中使用@PrePersist和@PreUpdate事件侦听器
在使用上述注释注释的方法中,检查集合的大小是否超过最大限制,是否删除最早的B项(可通过B的created_time time Stamp属性跟踪)
@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);
}
}
@Entity
public class B{
@ManyToOne
private A a;
}
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 `orphanRemoval` to true to tell JPA to remove the B 's DB records after its corresponding instances are removed from the B collection.