Create instance of the Entity in the Many side of ManyToOne Relationship

2.3k views Asked by At

I'm using 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 = new Contact();
contact.setOwner(?);

But while creating I will have only 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).

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.

I don't want to query Person Table with owner_id and set that "Person" reference to set while creating contact.

I want to use owner_id while inserting and owner reference with which I may get owner details for a give contact. How to solve this.

Thanks in Advance.

2

There are 2 answers

0
Sai Surya Kattamuri On BEST ANSWER
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).

2
JB Nizet On

You need a User. This User is in the database. JPA allows mapping rows of database tables to entities. You have the ID of this user. So... just get the user using the 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.