DominicEU
DominicEU

Reputation: 3631

Java Hibernate Annotation @JoinTable Relationships

I've recently started using Hibernate and am trying to get my head around all the annotations and ensure I do things properly. I have two tables 'user' and 'user_friends' that are similar to the below

+------+------+-------+
| id   | name | email |
+------+------+-------+

and the user friends table

+--------+---------+----------+
| userid | buddyid | accepted |
+--------+---------+----------+

Now in SQL I ran a query that looked similar to

SELECT u.id AS id, u.name AS username, u.email AS email FROM user_friends 
INNER JOIN users AS u ON u.id = '1' WHERE buddyid = '2' AND ACCEPTED = 1 UNION ALL 
SELECT u.id as id, u.name AS username, u.email AS email FROM user_friends
INNER JOIN users AS u ON u.id = '2' WHERE buddyid = '1' AND ACCEPTED = 1;

I've got two classes in Java set-up in a fashion similar to this

@Entity
@Table(name="users")
public class User {

  @Id
  @GeneratedValue
  private int id;

  private int name;
  private int email;

  @OneToMany(fetch=UserBuddy.class, mappedBy="user", fetch=FetchType.LAZY)
  @JoinColumn(name="userid")
  private Set<UserBuddy> _buddies;
}

@Entity
@Table(name="user_friends")
public class UserBuddy {

   @ManyToOne
   @JoinColumn(name="id")
   private User friendId;

   private int id;
   private int name;
   private int email;
}

I don't know how I would then go about, getting the user_friends name and email from the user table. Can anyone offer any help?

Upvotes: 0

Views: 637

Answers (1)

jeff
jeff

Reputation: 4333

Since you have the User object in your UserBuddy, just reference that

@Entity
@Table(name="user_friends")
public class UserBuddy 
{

   @ManyToOne
   @JoinColumn(name="id")
   private User friend; // This is a User not an id

   public String getEmail()
   {
     return friend.getEmail();
   }
}

Upvotes: 1

Related Questions