Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9221165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T03:31:04+00:00 2026-06-18T03:31:04+00:00

I’m having a hard time creating the optimal JPA representation of a relationship. Seems

  • 0

I’m having a hard time creating the optimal JPA representation of a relationship. Seems like there is a bunch of ways to do it and I’m not sure which is most optimal. Without JPA I might represent the structure as a PERSON table and a FRIEND table. Let’s say the PERSON table just has an ID and NAME. The FRIEND table has an OWNER_ID, a PERSON_ID, and a settable boolean IS_ACTIVE field. OWNER_ID and PERSON_ID both refer to the PERSON table. A person can have many friends so the unique primary key would be on OWNER_ID and PERSON_ID. In my code I would like the PersonEntity to control the relationship. Operations in Java might look like this:

person1.getFriends().add( new Friend( person2, isActive ) );
Friend friend = person1.findFriend( person2ID );

Something like that. Note that I would like JPA to implicitly assign the OWNER of the friend relationship. In the above code I do not pass it in the Friend constructor, I only pass the PERSON part of the composite key.

Here was my first guess at this:

@Entity
public class Person {
   @Id
   @GeneratedValue
   private Long id;

    @OneToMany( mappedBy="key.owner", cascade=CascadeType.ALL, orphanRemoval = true)
    private Set<Friend> friends = new HashSet<>();

    // getter and setter for Friends
    ...
}

@Entity
public class Friend {
   @EmbeddedId
   private Key key = new Key();

   private boolean isActive;

   ...

   @Embeddable
   public static class Key implements Serializable {
      @ManyToOne
      private Person owner;

      @OneToOne
      private Person person;

      ...
   }
}

But when I use this code I get stack overflow errors. I’m assuming it is confused by the OneToOne relationship.

What is the best way to model this sort of relationship in JPA 2.0? I suppose the simplest thing would be to introduce a generated long key in Friend. But that seems like it will make the query more complex for “find friends for john” since I will be introducing a third mapping table, basically mapping the relationship twice in SQL. Another approach is to make it a unidirectional OneToMany relationship and not even specify OWNER explicitly in Friend. That would introduce another table for the mapping and make queries a little convoluted. Using ElementCollection instead of OneToMany seems straight forward but then my understanding is that I could not manage Friend as an entity?

Let me know if you guys need anymore detail or requirements. BTW, I tried putting a MapsId in Friend for the Owner part of the PKEY but that gave me runtime errors.

Any help is appreciated.

NOTE: Even if I add a generated key to Friend I would like to enforce the uniqueness on the combination of {owner,person} in the Friend entity.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T03:31:06+00:00Added an answer on June 18, 2026 at 3:31 am

    Alright, so if you want a solution to this problem that creates the sort of table one would want to in pure SQL – that is no artificial surrogate key and application data as a compound key – you can definitely do it. However, using JPA makes this a little bit messier than you might want it to be.

    Thanks to @JB Niznet for his great input, you can definitely also do this by introducing a surrogate key as he suggests. The solution below just removes that need and as far as I can tell has no drawbacks.

    @Entity
    public class Person {
       @Id
       @GeneratedValue
       private Long id;
    
       @OneToMany( mappedBy="owner", cascade=CascadeType.ALL, orphanRemoval = true)
       private Set<Friend> friends = new HashSet<>();
    
       // getter and setter for Friends
       ...
    }
    
    @Entity
    public class Friend {
       @EmbeddedId
       private Key key = new Key();
    
       @ManyToOne
       @Maps("ownerId")
       private Person owner;
    
       @ManyToOne
       @MapsId("personId")
       private Person person;
    
       private boolean isActive;
    
       ...
    
       @Embeddable
       public static class Key implements Serializable {
          private Long ownerId;
          private Long personId;
    
          ...
       }
    } 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I've tracked down a weird MySQL problem to the two different ways I was
I know there's a lot of other questions out there that deal with this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.