I have a Hibernate class called Expression (开发者_如何学Csimplified 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"
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!
You should use the @ManyToMany relation here
精彩评论