There are a lot of information and examples how to use @ManyToMany
and this part is clear in general. I have not found elegant solution for my case. I know how to use work around, but I hope anyone knows and can share elegant solution or idea which should be used..
Income details:
Account table
@Entity
@Table(name = "account_table")
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_gen")
@SequenceGenerator(name = "account_seq_gen", sequenceName = "ACCOUNT_SEQ")
private Long id;
@ManyToMany(cascade = CascadeType.REMOVE)
@JoinTable(name = "account_calendar_relation",
joinColumns = @JoinColumn(name = "account_id"),
inverseJoinColumns = @JoinColumn(name = "calendar_id")
)
private List<Calendar> calendars = new ArrayList<>();
//...
}
is related to Calendar
@Entity
@Table(name = "calendar")
public class Calendar {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "calendar_seq_gen")
@SequenceGenerator(name = "calendar_seq_gen", sequenceName = "CALENDAR_SEQ")
private Long id;
@ManyToMany(mappedBy = "calendars")
private List<Account> accounts;
//...
}
as manyToMany.
Special restrictions
Loading account info I want to access all mapped calendars (for the account) but I'm not interested to have access to all accounts mapped on any accessed calendar via the account. I need situation to emulate some special behavior:
- Loading Account for User I'm interested to access correspond Calendar collection.
- Following 1. via calendar I need to know only the Account (for current user it doesn't matter if Calendar has a lot of relations to other Accounts).
- Deleting Account all Calendars should be removed in cascade.
- Calendars cascade deleting should be activated in Account deleting time in case if it was last Account for the Calendar.
- Adding calendars to Account all calendars should be added in cascade way.
- Restriction for 5. only link should be added for calendars that were persisted before for other Accounts.
Question
All this cases handlers I can implement in spring services. But I believe this issue can be solved on hibernate level and I trust that solution must be implemented in most elegant way. So please help me to handle or suggest me please approach to manage this cases in best way (some hibernate annotations or other tools).