gpt4 book ai didi

Java Hibernate 注解 @JoinTable 关系

转载 作者:行者123 更新时间:2023-12-01 15:17:06 26 4
gpt4 key购买 nike

我最近开始使用 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 姓名和电子邮件。有人可以提供任何帮助吗?

最佳答案

由于您的 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();
}
}

关于Java Hibernate 注解 @JoinTable 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com