Problem statement: CRUD a Message with multiple Categories without the CRUD operations affecting the Category.
I've got two tables: Category and Message. The Category table is intended to be specific to the user account and will be shared across several features, similar to 'tags'. The Message table is specific to a feature and is tagged with 0..* Categories. The Category table doesn't require any knowledge of which feature is referencing it so I've created an associative table to store the relations, Cat_Msg, which has references the PK of each table.
|---------|
|Category |
|_________|
|
|
|--------|
|Cat_Msg |
|________|
|
|
|--------|
|Message |
|________|
The issue I'm having is in the Message model for Hibernate. I either get this exception:
org.hibernate.TransientObjectException: object references an unsaved transient instance
Or if I add the cascade = CascadeType.ALL to the Message annotation it then deletes the Category when deleting the Message.
I think the issue is similar to this but I've got the issue where the Category doesn't have entries for the Message so I can't swap ownership. Or this site, but I don't want the associative table data, I need the Category.
Code example:
@XmlRootElement
@Entity(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
}
@XmlRootElement
@Entity(name = "message")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String message;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "cat_msg", joinColumns = { @JoinColumn(name = "cat_id", referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "msg_id", referencedColumnName = "id") })
private Collection<Category> categories;
}
I realise the CascadeType.ALL is causing the deletion of Category entries but I don't know how to resolve it so as not to get the hibernate exception and achieve what I need.