创建时,JPA ManyToMany不会插入连接表

时间:2016-06-26 07:27:34

标签: java mysql hibernate jpa

我使用的是JPA 2.1,mysql。

实体Usuario

@Entity
@Table(name = "USUARIO")
public class Usuario {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID_USUARIO")
    private Integer id;

    @Column(name = "NOMBRE", length = 30)
    private String nombre;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "integrantes", cascade = {CascadeType.ALL})
    private List<NucleoFamiliar> nucleosFamiliares;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "integrantes", cascade = {CascadeType.ALL})
    private List<GrupoJaas> gruposJaas;

    ... getters setters
}

实体GrupoJaas

@Entity
@Table(name = "GRUPO_JAAS")
public class GrupoJaas {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID_GRUPO_JAAS")
    private Integer id;

    @Column(name = "NOMBRE", length = 30)
    private String nombre;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "INTEGRANTE_GRUPO_JAAS", joinColumns = {
        @JoinColumn(name = "ID_GRUPO_JAAS") }, inverseJoinColumns = @JoinColumn(name = "ID_USUARIO"))
    private List<Usuario> integrantes;

    ... getters setters
}

实体NucleoFamiliar

@Entity
@Table(name = "NUCLEO_FAMILIAR")
public class NucleoFamiliar {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID_NUCLEO_FAMILIAR")
    private Integer id;

    @Column(name = "NOMBRE", length = 100)
    private String nombre;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "INTEGRANTE_NUCLEO_FAMILIAR", joinColumns = {
        @JoinColumn(name = "ID_NUCLEO_FAMILIAR") }, inverseJoinColumns = @JoinColumn(name = "ID_USUARIO"))
    private List<Usuario> integrantes;

    ... getters setters
}

当我创建一个新的&#34; NucleoFamiliar&#34;使用非空列表&#34; integrantes&#34;,jpa按预期执行2个句子:

insert into NUCLEO_FAMILIAR
insert into INTEGRANTE_NUCLEO_FAMILIAR

当我创建一个新的&#34; Usuario&#34;使用非空列表&#34; gruposJaas&#34;,jpa只执行一个句子:

insert into USUARIO

为什么不执行插入到INTEGRANTE_GRUPO_JAAS !! ???

两个代码(创建&#34; NucleoFamiliar&#34;以及创建&#34; Usuario&#34;)几乎相同,我的意思是,它们几乎相同。

请帮助,我花了几天时间看一切,但我还没有找到解决方案(我使用的是jpa 2.1)

1 个答案:

答案 0 :(得分:2)

在Usario类中,通过使用@ManyToMany关联映射中的mappedBy属性,您已指定了两个关联的所有者。

在以下两个关联映射中

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0'
    defaultConfig {
        applicationId "com.example.mytest"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"

        //for using java 8 and it's features like lambda expressions
        jackOptions { enabled true }


    }

 compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
        sourceCompatibility JavaVersion.VERSION_1_8
    }

通过在关系中使用mappedBy属性,您已经有效地指定了这些关联的所有者是GrupoJass和NucleoFamiliar。

现在在关系中,所有者只能更新关系状态。因此,当您保存NucleoFamiliar时,它还会更新JoinTable的关系。