0

我最近开始使用 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 表中获取 user_friends 名称和电子邮件。任何人都可以提供任何帮助吗?

4

1 回答 1

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();
   }
}
于 2012-07-13T16:32:06.073 回答