Hi there,
I have an many-to-many relationship, to which I want to add an additional table. I'm using the instructions here
viewtopic.php?f=1&t=950062&start=0In my many-to-many relationship, I also want the ID to be the connection of the both connected many-to-many relationship. The problem is that, when I create the @IdClass to define this, Hibernate wants to save the whole object to db and not just the id of the entity.
So my question is, how do I tell to hibernate that I want to save only the ID of the object to database, not the whole object?
Here are my classes:
@Entity
public class User implements Serializable {
@OneToMany (targetEntity=Friend.class,mappedBy="user")
private List<Friend> friends = new LinkedList<Friend>();
//I have tried with and without this component, I don't need this if Hibernate doesn't require it
@OneToMany (targetEntity=Friend.class,mappedBy="friend")
private List<Friend> otherFriends = new LinkedList<Friend>();
@Id @GeneratedValue (strategy = GenerationType.AUTO)
private Integer id;
... the getters and setters etc. other data...
}
@Entity
@IdClass(FriendId.class)
public class Friend implements Serializable {
@NotNull
private boolean pending;
@Id
@ManyToOne
@NotNull
private User user;
@Id
@ManyToOne
@NotNull
private User friend;
...the getters and setters ...
}
I have two solutions for the Friend Primary key table:
This one doesn't let the Hibernate to insert the table, but says:
BLOB/TEXT column ‘friend’ used in key specification without a key length
public class FriendId implements Serializable {
private User user,friend;
... the getters and setters...
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
else if (o instanceof FriendId) {
return friend.equals(((FriendId)o).friend) &&
user.equals(((FriendId)o).user);
}
return false;
}
@Override
public int hashCode() {
return user.hashCode() ^ friend.hashCode();
}
}
This one creates the table but Hibernate doesn't understand that only the user-id is stored, but looks for the whole object from the database
public class FriendId implements Serializable {
private int user,friend;
... the getters and setters...
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
else if (o instanceof FriendId) {
return friend == ((FriendId)o).friend &&
user == (((FriendId)o).user);
}
return false;
}
@Override
public int hashCode() {
return user ^ friend;
}
}
Thanks,
Jesse