Hi,
i have a problem to map a directed graph between objects. I have the following Mapping Description added to an object:
Code:
@Entity
@Table(name="USER")
public class User {
@Id
@Column(name = "ID", nullable = false)
private long Id;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "FOLLOWERS", joinColumns = { @JoinColumn(name = "FRIEND_ID") })
@ForeignKey(name = "none")
@Column(name = "FOLLOWES_ID", nullable = false)
@SQLInsert(sql = "INSERT IGNORE INTO FOLLOWERS (FOLLOWES_ID, FRIEND_ID) VALUES (?,?)")
@SQLDelete(sql = "DELETE FOLLOWERS WHERE FOLLOWES_ID = 1 and 1<>2")
@SQLUpdate(sql = "UPDATE FOLLOWERS WHERE FOLLOWES_ID = 1 and 1<>2")
private Set<Long> followers = new HashSet<Long>();
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "FOLLOWERS", joinColumns = { @JoinColumn(name = "FOLLOWES_ID") })
@ForeignKey(name = "none")
@Column(name = "FRIEND_ID", nullable = false)
@SQLInsert(sql = "INSERT IGNORE INTO FOLLOWERS (FRIEND_ID, FOLLOWES_ID) VALUES (?,?)")
@SQLDelete(sql = "DELETE FOLLOWERS WHERE FRIEND_ID = 1 and 1<>2")
@SQLUpdate(sql = "UPDATE FOLLOWERS WHERE FRIEND_ID = 1 and 1<>2")
private Set<Long> friends = new HashSet<Long>();
// Getter and Setters
}
Code:
// user1 with a follower relation to user2
User user1 = new User();
user1.setId(1l);
user1.getFollowers().add(2l);
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(user1);
transaction.commit();
// Create and save previously unsaved user but not set the Friend relation to user1
User user2 = new User();
user2.setId(2l);
transaction = session.beginTransaction();
session.saveOrUpdate(user2);
transaction.commit();
// Load user2 from db and user2 friends is empty (same for followers of user1)
User user2loaded = (User) session.byId(User.class).load(2l);
System.out.println(user2loaded.getFriends().toString() + user2loaded.getFollowers().toString());
The @SQLInsert is getting used, but neither the @SQLDelete nor the @SQLUpdate. I don't want to delete anything in the FOLLOWERS table.
I know this is a little bit awkward mapping. But not all objects are always available and followers/friends can be empty (or not complete) but should never trigger any deletion. Is this even possible with Hibernate?
Thank for your help!