Help setting up entity bean with complex PK
dornus Sep 6, 2005 2:34 PMI have just gone through the demos and trails and cannot find anything explaining the way to correctly setup a compound primary key for this particular situation. Below is a simple example of what I am trying to do.
I have 2 tables, (user and blocklist). The primary key of the user table is userId. The compound primary key of the blocklist is ownerId and blockedId. Both ownerId and blockedId are foreign keys which reference userId. This is shown below:
Table 1 - "user"
userId - Primary Key (int - autogenerated by database)
firstName varchar(30)
Table 2 - "blocklist"
ownerId (FK mapped to userId of table 'user')
blockedId (FK mapped to userId of table 'user')
timestamp (created when a record is inserted)
I am guessing this is a many-to-many relationship. This is based on the fact that:
- An ownerId can have multiple blockedIds.
- A blockedId can appear for multiple ownerIds.
This is what I have coded so far. I keep getting errors (which I assume have to do with the mappings). Where am I going wrong?
###############
# User Entity Bean
###############
@Entity
@Table(name = "user")
public class User {
@Id(generate = GeneratorType.AUTO)
@Column(name = "userId")
public long getUserId() {
return userId;
}
//etc...
}
###############
# Blocklist Entity Bean
###############
@Entity
@Table(name = "blocklist")
public class Blocklist implements Serializable {
private BlocklistPK blocklistPK;
private Timestamp date;
@EmbeddedId
public BlocklistPK getBlocklistPK() {
return blocklistPK;
}
//etc...
}
###############
# Blocklist Compund PK
###############
@Embeddable
public class BlocklistPK implements Serializable {
private User ownerId;
private User blockedId;
@ManyToMany
@JoinColumn(name="ownerId",nullable=false)
public User getOwnerId(){
return ownerId;
}
@ManyToMany
@JoinColumn(name="blockedId",nullable=false)
public User getBlockedId(){
return blockedId;
}
public int hashCode(){
return ownerId.hashCode() + blockedId.hashCode();
}
public boolean equals(Object obj){
if (obj == null){
return false;
}
else if (obj == this){
return true;
}
else if (!(obj instanceof BlocklistPK)){
return false;
}
BlocklistPK pk = (BlocklistPK) obj;
return pk.ownerId.equals(ownerId) && pk.blockedId.equals(blockedId);
}
//etc...
}
############
I have gotten such errors as:
org.hibernate.MappingException: Could not determine type for: par.User, for columns: [org.hibernate.mapping.Column(userId)]
and
org.hibernate.AnnotationException: par.User collection not yet supported: par.BlocklistPKownerId
and
java.util.NoSuchElementException
and
java.lang.NullPointerException
These errors depend on if I set the BlocklistPK columns to OneToOne,OneToMany,ManyToOne or ManyToMany
Can anyone help me figure out what I am doing wrong?
Thanks!