JPA很多很多人没有坚持关联表

时间:2014-01-07 16:11:52

标签: spring hibernate jpa

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

    @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());
    }

我正在使用lans断言获取NPE,我正试图从KMLFolder.getName()检索Locations其他断言正在工作,我从Location获取KMLFolder名称{1}}。

以下是我的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表。对于为什么会发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:1)

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

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