【问题标题】:JPA manyToMany not persisting in assocation tableJPA manyToMany 没有保留在关联表中
【发布时间】:2014-01-07 16:11:51
【问题描述】:

我正在尝试以下单元测试:

    @Test
    @Transactional
    public void thatFolderLocationAssociationTableIsWorking() {
        Location l1 = new DomesticLocation();
        l1.setDeptName("Test name 1");
        Location l2 = new DomesticLocation();
        l2.setDeptName("Test name 2");

        KMLFolder k1 = new KMLFolder();
        k1.setName("Test name 1");
        KMLFolder k2 = new KMLFolder();
        k1.setName("Test name 2");

        List<Location> locations = new ArrayList<Location>();
        locations.add(l1);
        locations.add(l2);
        k1.setLocations(locations);
        kmlFolderServiceImpl.save(k1);

        assertEquals("Test name 1", kmlFolderServiceImpl.find(1L).getLocations().get(0).getDeptName());
        assertEquals("Test name 2", kmlFolderServiceImpl.find(1L).getLocations().get(1).getDeptName());

                //The following line gets the NPE
        assertEquals("Test name 1", locationServiceImpl.find(1L).getKmlFolderList().get(0).getName());
    }

我正在尝试从 Locations 检索 KMLFolder.getName() 的最后一个断言上的 NPE 其他断言正在工作,我从 KMLFolder 获得 Location 名称。

这是我的 JPA 定义:

@ManyToMany(mappedBy="kmlFolderList", cascade=CascadeType.ALL)
private List<Location> locations = new ArrayList<Location>();

@ManyToMany
@JoinTable(name="LOCATION_KMLFOLDER",
    joinColumns={@JoinColumn(name="KMLFOLDER_ID", referencedColumnName="ID")},
    inverseJoinColumns={@JoinColumn(name="LOCATION_ID", referencedColumnName="ID")}
)

运行测试时正在创建相应的表。这是控制台输出:

Hibernate: 
    create table project.LOCATION_KMLFOLDER (
        KMLFOLDER_ID bigint not null,
        LOCATION_ID bigint not null
    ) ENGINE=InnoDB 
...
Hibernate: 
    alter table project.LOCATION_KMLFOLDER 
        add index FK_lqllrwb2t5cn0cbxxx3ms26ku (LOCATION_ID), 
        add constraint FK_lqllrwb2t5cn0cbxxx3ms26ku 
        foreign key (LOCATION_ID) 
        references project.KMLFolder (id)
Hibernate: 
    alter table .LOCATION_KMLFOLDER 
        add index FK_ckj00nos13yojmcyvtefgk9pl (KMLFOLDER_ID), 
        add constraint FK_ckj00nos13yojmcyvtefgk9pl 
        foreign key (KMLFOLDER_ID) 
        references project.Locations (id)

控制台没有像我预期的那样显示对 LOCATION_KNLFOLDER 表的插入。关于为什么会发生这种情况的任何想法?

【问题讨论】:

    标签: spring hibernate jpa


    【解决方案1】:

    您正在初始化 Hibernate 忽略的关联的反面,而不是(或除此之外)初始化 Hibernate 不会忽略的关联的所有者。

    所有者方是没有mappedBy 属性的一方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2011-08-03
      • 2011-07-21
      相关资源
      最近更新 更多