JPA Unidirectional ManyToMany无法删除

时间:2015-12-02 10:52:43

标签: jpa many-to-many eclipselink glassfish-4

我正在使用EclipseLink 2.6.1开发在GlassFish 4.1.1上运行的Web应用程序。我在Users和Projects之间有一个单向的ManyToMany关系,当我从User.projects中删除元素并合并User时,数据库中的连接行不会被删除。我制作了一个较小的演示应用程序来隔离它:

用户类:

@Entity
@Table(name = "demouser")
public class DemoUser implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DemoUserSeq")
    @SequenceGenerator(name = "DemoUserSeq", sequenceName = "demouser_userid_seq", allocationSize = 1)
    @Column(name = "userid")
    private Integer id;
    @Column(name = "username")
    private String userName;
    // some more fields
    @JoinTable(name = "demouserprojbind", joinColumns = {
        @JoinColumn(name = "username", referencedColumnName = "username")
    }, inverseJoinColumns = {
        @JoinColumn(name = "projcode", referencedColumnName = "projcode")
    })
    @ManyToMany
    private Set<DemoProject> projects;

DemProject没有向用户映射ManyToMany。绑定表&#34; demouserprojbind&#34;绑定唯一(非空)文本列而不是串行PK。

演示更新代码:

DemoUser user = getUser(username); // EntityManager Query by username
Set<DemoProject> userProjects = user.getProjects();
userProjects.clear();
EntityManager em = emf.createEntityManager();
utx.begin();
em.joinTransaction();
em.merge(user);
em.flush();
utx.commit();
em.close();

这是在Servlet中生成的演示代码 - emf和utx,并注入了EntityManagerFactory和UserTransaction。

当我从EclipseLink跟踪SQL时,它看起来像这样:

DELETE FROM demouserprojbind WHERE ((projcode = ?) AND (username = ?))
bind => [Project2, null]
DELETE FROM demouserprojbind WHERE ((projcode = ?) AND (username = ?))
bind => [Project1, null]

显然无法输入拥有实体的用户名 - SQL不匹配任何行,因此不会从数据库中删除任何行。

我的保存逻辑中是否有任何错误(我想删除用户和项目之间的绑定,但用户和项目本身应该保留),还是EcliseLink中的错误?

1 个答案:

答案 0 :(得分:0)

在你的

Revisions

放入anotation ManyToMany级联类型,如下所示:

@ManyToMany
private Set<DemoProject> projects;