问题
I've got two tables A
and B
with simple PK's.
@Entity
public class A {
@Id
public int idA;
}
@Entity
public class B {
@Id
public int idB;
}
I want to map a new association class AB that simply stores the relations between A
and B
, with composite PK idA
+idB
. AB
doesn't have any extra columns, just the relation between idA
and idB
.
Is it possible to map AB
using a single class? I want to avoid having to create a new ABId
class just to use it as @IdClass
or @EmbeddedId
in AB
, and I don't want to map this with a @ManyToMany
association on A
or B
.
回答1:
Why do you want to map such a join table? Just use a ManyToMany association between A and B. This join table will then be handled automatically when you'll add/remove a B to/from the list of Bs contained in A.
See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e11402
If you really want to do that, then just map the two IDs with the @Id notation. The primary class will be the entity class itself (which must be serializable), as explained in the hibernate reference documentation. Note that this is Hibernate-specific.
回答2:
It would be nice if @JBNizet 's suggestion worked. Unfortunately, there's an old bug which makes it impossible to adopt it in the version I'm using (3.3.1-GA)
I've finally sorted this out by defining an inner static ID class and using it as @IdClass
:
@Entity
@Table(name="TABLE_AB")
@IdClass(value=ClassAB.ClassABId.class)
public class ClassAB implements Serializable {
private String idA;
private String idB;
@Id
public String getIdA(){ return idA; }
public void setIdA(String idA){ this.idA = idA; }
@Id
public String getIdB(){ return idB; }
public void setIdB(String idB){ this.idB = idB; }
static class ClassABId implements Serializable {
private String idA;
private String idB;
@Column(name="ID_A")
public String getIdA(){ return idA; }
public void setIdA(String idA){ this.idA = idA; }
@Column(name="ID_B")
public String getIdB(){ return idB; }
public void setIdB(String idB){ this.idB = idB; }
// HashCode(), equals()
}
}
This way I don't have to define a new public class, and I don't have to modify the mappings file to include the ID class.
来源:https://stackoverflow.com/questions/7793169/mapping-a-class-that-consists-only-of-a-composite-pk-without-idclass-or-embedd