我有这个映射:
实体 1 实体 2 实体 3
和实体 4
实体编号 1,2 和 3 有一个实体 4 的列表。实体 4 只有 2 个字段:一个字符串(数据)和一个我设置为 @Id 和 @GeneratedValue 的 Id
在包含实体 4 数据的数据库表中,我不希望 String(DATA) 重复。
但是实体 1,2 和 3 可以在它们的实体 4 列表中具有它们之间的重复数据。
一个示例(实例是指定实体的对象):
Instance 1 (Entity 1): List: ["hi","hello","music"]
Instance 2 (Entity 2): List: ["tv","hi","sofa"]
Instance 3 (Entity 2): List: ["sofa","wii"]
Instance 4 (Entity 3): List: ["music","otherString"];
实体 4 的 db 表条目应该是:
ID 字符串
1 hi
2 hello
3 music
4 tv
5 sofa
6 wii
7 otherString
我得到的是:
ID 字符串
1 hi
2 hello
3 音乐
4 电视 5 hi 6 沙发
7 沙发 8 wii
9 音乐
10 otherString
数据重复。当我尝试使用 @Id 注释提供字段字符串时,当我尝试保存实体 1,2 或 3 的实例及其列表中已经存在的字符串时,它会发送实体 4 的重复条目错误并执行不保存实体 1,2 或 3。
我该如何正确注释呢?
我的一些代码:
实体 1,2 或 3(在这部分代码中它们都是相同的):
@Entity
public class Entity1 {
private List<Entity4> entity4List;
@OneToMany(targetEntity=Entity4.class,cascade =CascadeType.ALL)
public List<Entity4> getEntity4List() {
return entity4List;
}
}
实体 4:
@Entity
public class Entity4 {
private long id;
private String stringn;
@Id
@GeneratedValue
public long getId() {
return id;
}
}
还有我保存实体 1,2 或 3 的休眠代码:
public void addEntity1(ArrayList<String> list){
List<Entity4> L = new ArrayList<Entity4>();
for(String s:list)
{
L.add(new Entity4(s));
}
Entity1 e=new Entity1(L);
Session session = sf.getCurrentSession();
session.beginTransaction();
session.save(e);
session.getTransaction().commit();
}