当我只需要一个主键时,Hibernate 会创建两个主键
我有一个名为 Expression 的 Hibernate 类(此处进行了简化,以便您观看):
@Entity
public class Expression {
@Id
@GeneratedValue
private long id;
private String data;
@OneToMany(fetch=FetchType.EAGER)
@Cascade({CascadeType.MERGE, CascadeType.PERSIST})
private Set<Expression> dependencies;
}
这将创建两个表,Expression(id, data)
和 Expression_Expression(expression_id, dependency_id)
。但是,Hibernate 将 expression_id 和 dependency_id 列设置为主键,因此我不能有重复的 dependency_id,这正是我想要的。
例如,如果我有三个表达式:
Expression x = new Expression("0");
Expression y = new Expression("1");
Expression z = new Expression("x + y");
Set<Expression> tmp = new HashSet<Expression>();
tmp.add(x);
tmp.add(y);
z.setDependencies(tmp);
// Persist x, y, and z.
那么 Hibernate 将执行以下操作:
将 x
插入 id = 1 且 data = "0"
的 Expression
表中 将 y
插入到 id = 2 且 data = "1"
的 Expression
表中 将 z
插入到 id = 3 且 data = "a + b"
的 Expression
表中 使用 expression_id = 3 和 dependency_id = 1 在“Expression_Expression”表中插入一行。(使 z
成为 x
的依赖项。)
但是当它尝试将一行插入到当表达式_id = 3 且 dependency_id = 2 的 Expression_Expression
表(使 z
成为 y
的依赖项)时,我收到重复条目错误。
我希望能够在 Expression_Expression
表中包含具有相同 expression_id
值的多行。
任何帮助将不胜感激!
I have a Hibernate class called Expression (simplified here for your viewing pleasure):
@Entity
public class Expression {
@Id
@GeneratedValue
private long id;
private String data;
@OneToMany(fetch=FetchType.EAGER)
@Cascade({CascadeType.MERGE, CascadeType.PERSIST})
private Set<Expression> dependencies;
}
This creates two tables, Expression(id, data)
and Expression_Expression(expression_id, dependencies_id)
. However, Hibernate sets both the expression_id and dependencies_id columns as the primary key so I can't have a duplicate dependencies_id, which is what I'd like.
For example, if I have three Expressions:
Expression x = new Expression("0");
Expression y = new Expression("1");
Expression z = new Expression("x + y");
Set<Expression> tmp = new HashSet<Expression>();
tmp.add(x);
tmp.add(y);
z.setDependencies(tmp);
// Persist x, y, and z.
then Hibernate will perform the following:
Insert x
into the Expression
table with id = 1 and data = "0"
Insert y
into the Expression
table with id = 2 and data = "1"
Insert z
into the Expression
table with id = 3 and data = "a + b"
Insert a row into the 'Expression_Expression' table with expression_id = 3 and dependencies_id = 1. (Making z
a dependent of x
.)
But when it tries to insert a row into the Expression_Expression
table with expression_id = 3 and dependencies_id = 2 (making z
into a dependent of y
) I get a duplicate entry error.
I'd like to be able to have multiple rows in the Expression_Expression
table with the same expression_id
value.
Any assistance would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在这里使用 @ManyToMany 关系
You should use the @ManyToMany relation here