Java Hibernate Annotation @JoinTable Relationships

时间:2012-07-13 16:00:02

标签: java sql hibernate join

我最近开始使用Hibernate,并试图了解所有注释并确保我正确地做事。我有两个表'user'和'user_friends',类似于下面的

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

和用户朋友表

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

现在在SQL中我运行了一个类似于

的查询
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;

我在Java设置中有两个类似于

的方式
@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;
}

我不知道如何进行,从用户表中获取user_friends名称和电子邮件。任何人都可以提供任何帮助吗?

1 个答案:

答案 0 :(得分:1)

由于UserBuddy中有User对象,因此只需引用

@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();
   }
}