Dreikäsehoch
Dreikäsehoch

Reputation: 131

JPA ManyToMany Entity is not persisted

I have following two entities:

@Entity
@Table(name = "mailinglist")
public class MailingList {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String name;

@ManyToMany(fetch = FetchType.EAGER,cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE
})
@JoinTable(
    name = "has_account",
    joinColumns = @JoinColumn(name = "mailinglist_name"),
    inverseJoinColumns = @JoinColumn(name = "account_id"))
private List<EmailAccount> accounts;

and

@Entity
@Table(name = "emailaccount")
public class EmailAccount {

@Id
@Column
private String email;

@ManyToMany(mappedBy = "accounts")
@Column
private List<MailingList> mailingLists;

Whenever I try to add new emails via a request, they are not persisted, although they are correctly parsed and stored. What could be the reason?

Please tell me what information you are missing if the question is not clear enough.

Upvotes: 0

Views: 315

Answers (1)

Lesiak
Lesiak

Reputation: 25936

See Hibernate Tips: How to map a bidirectional many-to-many association

Bidirectional associations are easy to use in queries, but they also require an additional step when you persist a new entity. You need to update the association on both sides when you add or remove an entity.

Updating the associations on both entities is an error-prone task. It’s, therefore, a good practice to provide helper methods for it.

@Entity
@Table(name = "mailinglist")
public class MailingList {

    // ...

    public void addEmailAccount(EmailAccount acc) {
        this.accounts.add(acc);
        acc.getMailingLists().add(this);
    }

    public void removeBook(EmailAccount acc) {
        this.accounts.remove(acc);
        acc.getMailingLists().remove(this);
    }
}

Upvotes: 3

Related Questions