简体   繁体   English

JPA 没有为多对多关系创建数据库条目

[英]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.现在,在使用 PhoenixPermission-Entity object 调用addPermission方法时,更新了 ArrayList 的“权限”,但“PLAYER_PERMISSION”表的数据库中没有新的元组。

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?有任何想法吗?

Found it.找到了。 I just had to update both objects.我只需要更新这两个对象。 Here is the updated addPermission method:这是更新后的addPermission方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM