Search code examples
javahibernateormspring-data-jpahibernate-onetomany

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


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.


Solution

  • 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).