简体   繁体   English

在ManyToOne关系的多边中创建实体的实例

[英]Create instance of the Entity in the Many side of ManyToOne Relationship

I'm using Spring Data JPA . 我正在使用Spring Data JPA
I have the following Entities 我有以下实体

Person Entity 实体

class Person{

private String id;

@OneToMany(mappedBy="owner")
private List<Contact> contacts;
...

}

And Contact Entity 联系实体

class Contact{

private String id;

@ManyToOne
@JoinColumn(name="owner_id")
private Person owner;
...

}

When I want to create Contact instance,I'm confused about how to map owner details. 当我想创建Contact实例时,我对如何映射所有者详细信息感到困惑。

Contact contact = new Contact();
contact.setOwner(?);

But while creating I will have only owner_id. 但是在创建时,我将只有owner_id。
I want to set owner_id alone while creating, but to have association(while querying) I have mapped it to concrete class(Person). 我想在创建时单独设置owner_id,但是要拥有关联(在查询时),我已将其映射到具体的类(人)。

I've tried this 我已经试过了

class Contact{

@Column("owner_id")
private String ownerId;
@ManyToOne
@JoinColumn("owner_id")
private Person pwner;

} 

But its throwing error duplicate reference to owner_id. 但是它的抛出错误重复了对owner_id的引用。

I don't want to query Person Table with owner_id and set that "Person" reference to set while creating contact. 我不想使用owner_id查询人员表,并在创建联系人时设置要设置的“人员”引用。

I want to use owner_id while inserting and owner reference with which I may get owner details for a give contact. 我想在插入和所有者引用时使用owner_id,我可以通过它获得给定联系人的所有者详细信息。 How to solve this. 如何解决这个问题。

Thanks in Advance. 提前致谢。

You need a User. 您需要一个用户。 This User is in the database. 该用户在数据库中。 JPA allows mapping rows of database tables to entities. JPA允许将数据库表的行映射到实体。 You have the ID of this user. 您具有该用户的ID。 So... just get the user using the JPA API: 所以...只需使用JPA API吸引用户:

contact.setOwner(entityManager.find(User.class, userId));

or 要么

contact.setOwner(entityManager.getReference(User.class, userId));

The first one actually gets the details of the User from the database, and thus checks the user indeed exists. 第一个实际上是从数据库中获取用户的详细信息,从而检查用户是否确实存在。

The second one assumes the user exists, ans just creates a lazily initialized proxy, without querying the database. 第二个假设用户存在,ans只是创建了一个延迟初始化的代理,而不查询数据库。

class Person {

   private String id;

   @OneToMany(mappedBy="owner")
   private List<Contact> contacts;

}

class Contact {

   private String id;

   @ManyToOne(fetch = FetchType.Lazy)
   @JoinColumn(name="owner_id", nullable=false,updatable=false)
   private Person owner;

   @Column("owner_id")
   private String ownerId;

}

This actually allows me to use ownerId:String field while creating a contact object and owner:Owner object helps me get the Owner Details for a given contact details(If needed).This way I can achieve my requirements without using findOne(id) or getOne(id) . 实际上,这允许我在创建联系人对象时使用ownerId:String字段,并且owner:Owner对象可以帮助我获取给定联系人详细信息的所有者详细信息(如果需要)。这样我就可以无需使用findOne(id)getOne(id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM