John_H_Smith
John_H_Smith

Reputation: 334

JPA not creating database entry for many to many relationship

I have these 2 classes (shortened):

@Entity
public class ClanPlayer {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private int id;
    @ManyToMany(mappedBy = "players")
    private List<PhoenixPermission> permissions = new ArrayList<>();

    public ClanPlayer() {}

    public List<PhoenixPermission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<PhoenixPermission> permissions) {
        this.permissions = permissions;
    }

    public void addPermission(PhoenixPermission permission) {
        EntityManager em = EMUtils.getEntityManager();
        em.getTransaction().begin();
        permissions.add(permission);
        em.getTransaction().commit();
    }
}

and

@Entity
public class PhoenixPermission {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private int id;
    @ManyToMany
    @JoinTable(name = "PLAYER_PERMISSION")
    private List<ClanPlayer> players = new ArrayList<>();

    public PhoenixPermission() {}

    public List<ClanPlayer> getPlayers() {
        return players;
    }

    public void setPlayers(List<ClanPlayer> players) {
        this.players = players;
    }
}

Now, while calling the addPermission method with a PhoenixPermission-Entity object, the ArrayList 'permissions' is updated, but there is no new tuple in the database of the 'PLAYER_PERMISSION' table.

The debug log doesn't show any insert queries for this table. All other Entity Manager operations are working fine. I assume there is something wrong with my annotations, but I am not sure about. Any ideas?

Upvotes: 0

Views: 328

Answers (1)

John_H_Smith
John_H_Smith

Reputation: 334

Found it. I just had to update both objects. Here is the updated addPermission method:

public void addPermission(PhoenixPermission permission) {
    EntityManager em = EMUtils.getEntityManager();
    em.getTransaction().begin();
    permissions.add(permission);
    permission.getPlayers().add(this);
    em.getTransaction().commit();
}

Upvotes: 1

Related Questions