【问题标题】:JPA onetomany on same entity同一实体上的 JPA onetomany
【发布时间】:2016-03-12 13:38:44
【问题描述】:

我正在尝试按如下方式创建实体

 @Data
    public class Person
    {
    @Id
    private String id;

@OneToMany(mappedBy="id")
 private List<person> friends;
    }

让 JPA 创建实体,我可以将有朋友的人坚持为空

当尝试保存已填充好友列表的新人时,该关系在 RDBMS 中不可见,并且在保存时不会引发任何错误。

无法弄清楚朋友数据是否真的被存储了?如果是,如何访问?

【问题讨论】:

  • mappedBy 应该指向其他类型的 Person 类型的字段。它没有。建议你去阅读一些 JPA 文档
  • 感谢您指出这一点 :-) 鉴于您在 JPA 方面的深厚“专业知识”,您能否告诉我如何映射上述关系?提前致谢!
  • 建议您查看 JPA 文档。任何 JPA 文档都会告诉您如何映射 1-N 双向关系。比如datanucleus.org/products/accessplatform_4_2/jpa/orm/…为什么这么难找?

标签: java jpa one-to-many


【解决方案1】:

假设您有两个表,PersonPerson_FriendsPerson 类如下所示:

注意:为了简单起见,我使用IDENTITY 作为GenerationTypeint 作为id 的数据类型。

@Entity
class Person
{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinTable(name="Person_Friends")
    List<Person> friends = new ArrayList<>();

    @Override
    public String toString() {
        return "Person [id=" + id + ", friends=" + friends + "]";
    }
}

使用friends 保存示例Person 对象的代码:

entityManager.getTransaction().begin();
Person p = new Person();
p.friends.add(new Person());
p.friends.add(new Person());
p.friends.add(new Person());
p.friends.add(new Person());
entityManager.persist(p);
entityManager.getTransaction().commit();

无法弄清楚朋友数据是否真的被存储了?

使用此架构,您应该能够在Person_Friends 表中找到朋友数据。

如果是,如何访问?

加载您要查看其好友数据的Person 对象也应填充friends 列表,尽管对于此映射是延迟的。

如果您想查看此处使用的自动生成表,请查看以下 DDL:

    create table Person (
        id integer generated by default as identity,
        primary key (id)
    )

    create table Person_Friends (
        Person_id integer not null,
        friends_id integer not null
    )

    alter table Person_Friends 
        add constraint UK_4ehyhs34ebu5gl6k8u5ckd2u7 unique (friends_id)

    alter table Person_Friends 
        add constraint FKjvrny03ut8h70garyw5ehnlr7 
        foreign key (friends_id) 
        references Person

    alter table Person_Friends 
        add constraint FK85ngln3801hk33fkhhsl7b8e7 
        foreign key (Person_id) 
        references Person

【讨论】:

  • 该代码似乎是 Hibernate API 而不是 JPA API,但问题确实说明了 JPA API。也许您应该更改它以反映问题?
  • @BillyFrost 这很好,因为问题标题表明 OP 对 JPA 感兴趣。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多