Java JPA-使用ElementCollection在列表中添加和删除元素
我将SQL中的字符串列表保留为@ElementCollection,我的主要用法类似于队列:Java JPA-使用ElementCollection在列表中添加和删除元素,java,list,hibernate,jpa,collections,Java,List,Hibernate,Jpa,Collections,我将SQL中的字符串列表保留为@ElementCollection,我的主要用法类似于队列: 从数据库中获取它 进行一些计算 删除第一个元素并在列表末尾插入新元素: this.measures.remove(0);本.测量.添加(测量) 将其保存到数据库中 当前实现的问题是删除第一个元素会更新列表(items\u order列)中所有元素的索引,这对性能非常不利。。。 还有别的办法吗?也许有可能有一个运行的索引(items\u order列),这样可以保持顺序,但不能在列表中定位 示例: 左至“
this.measures.remove(0);本.测量.添加(测量)代码>
将其保存到数据库中
当前实现的问题是删除第一个元素会更新列表(items\u order列)中所有元素的索引,这对性能非常不利。。。
还有别的办法吗?也许有可能有一个运行的索引(items\u order列),这样可以保持顺序,但不能在列表中定位
示例:
左至“:”是元素的索引,右至元素本身。
[0:“a”,1:“b”,2:“c”]
计算后,以下内容将插入数据库:
[0:“b”、1:“c”、2:“d”]-所有元素索引都已更新(性能不佳)
我不确定是否可能实施的可能解决方案:
[1:“b”、2:“c”、3:“d”]-所有元素保持相同的顺序id(仍然有序)
我的实体:
@实体
公共类商店{
@元素集合
@订单列
私人清单项目;
//塞特吸气剂
}
我最终做的是创建自己的实体,而不是使用注释创建字段表,这是存储实体:
@Entity
public class Store {
@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
@OrderBy("index ASC")
private List<Item> itemsList;
@Column
private int index = 0;
public List<Item> getItemsList() {
return itemsList;
}
public void setItemsList(List<Item> itemsList) {
this.itemsList = itemsList;
}
public void addToItemList(String item) {
final Item newItem = new Item();
newItem.setStoreId(this.id);
newItem.setValue(item);
newItem.setIndex(index++);
this.itemsList.add(newItem);
}
}
我最终做的是创建自己的实体,而不是使用注释创建字段表,这是存储实体:
@Entity
public class Store {
@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true)
@OrderBy("index ASC")
private List<Item> itemsList;
@Column
private int index = 0;
public List<Item> getItemsList() {
return itemsList;
}
public void setItemsList(List<Item> itemsList) {
this.itemsList = itemsList;
}
public void addToItemList(String item) {
final Item newItem = new Item();
newItem.setStoreId(this.id);
newItem.setValue(item);
newItem.setIndex(index++);
this.itemsList.add(newItem);
}
}
这应该对你有帮助这应该对你有帮助
@Entity
@IdClass(Ids.class)
public class Item {
@Id
private long storeId;
@Id
private int index;
@Column
private String value;
public long getStoreId() {
return storeId;
}
public void setStoreId(long storeId) {
this.storeId = storeId;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
class Ids implements Serializable { // each id will be composed of storeId + index
long storeId;
int index;
}