JPA:如何表示 JoinTable 和 JoinTable 的组合键?
JPA: How to represent JoinTable and composite key of a JoinTable?
假设我有一个网络应用程序,用户可以在其中关注其他用户。
在我的数据库中,我有一个 User
table 和一个 Following
table。
Following
table 只有两个值:followingUserId 和 followedUserId。
在 Java 中,我有一个用户 class。我看到的大多数教程都涉及一个对象,该对象包含与其相关的一组对象。这么多教程都可以描述如何让Users拥有一组用户关注该用户,以及一组用户关注一个用户。但这需要大量内存。
我正在考虑另一种结构,其中用户对象没有关于关注的信息。相反,有一个 Following 对象看起来像这样
@Entity
@Table(name = "Following")
public class Following {
RegisteredUser follower;
RegisteredUser followed;
}
并对应于联接table。当我想获得一个用户的所有关注者时,我可以查询以该用户为关注者的所有关注对象。
我的问题是:
Followers Table 有两个用户 ID 中的每一个的组合键。我如何使用注释来表示该组合键? @Id注解将单个变量表示为key
如何进行这样的查询?
如果相关,我使用 MySQL 作为 db
如果使用 JPA > 2.0,您可以将关系标记为您的 ID:
@Entity
@Table(name = "Following")
@IdClass(FollowingId.class)
public class Following {
@Id
RegisteredUser follower;
@Id
RegisteredUser followed;
}
public class FollowingId implements Serializable {
private int follower;
private int followed;
}
followingId class 中的类型必须与 RegisteredUser Id 的类型匹配。如果您搜索 JPA 派生 ID,则有很多更复杂的示例。
对于查询,这取决于您要查找的内容。可以使用 JPQL 获取特定用户的关注者集合:
"Select f.follower from Following f where f.followed = :user"
假设我有一个网络应用程序,用户可以在其中关注其他用户。
在我的数据库中,我有一个 User
table 和一个 Following
table。
Following
table 只有两个值:followingUserId 和 followedUserId。
在 Java 中,我有一个用户 class。我看到的大多数教程都涉及一个对象,该对象包含与其相关的一组对象。这么多教程都可以描述如何让Users拥有一组用户关注该用户,以及一组用户关注一个用户。但这需要大量内存。
我正在考虑另一种结构,其中用户对象没有关于关注的信息。相反,有一个 Following 对象看起来像这样
@Entity
@Table(name = "Following")
public class Following {
RegisteredUser follower;
RegisteredUser followed;
}
并对应于联接table。当我想获得一个用户的所有关注者时,我可以查询以该用户为关注者的所有关注对象。
我的问题是:
Followers Table 有两个用户 ID 中的每一个的组合键。我如何使用注释来表示该组合键? @Id注解将单个变量表示为key
如何进行这样的查询?
如果相关,我使用 MySQL 作为 db
如果使用 JPA > 2.0,您可以将关系标记为您的 ID:
@Entity
@Table(name = "Following")
@IdClass(FollowingId.class)
public class Following {
@Id
RegisteredUser follower;
@Id
RegisteredUser followed;
}
public class FollowingId implements Serializable {
private int follower;
private int followed;
}
followingId class 中的类型必须与 RegisteredUser Id 的类型匹配。如果您搜索 JPA 派生 ID,则有很多更复杂的示例。
对于查询,这取决于您要查找的内容。可以使用 JPQL 获取特定用户的关注者集合:
"Select f.follower from Following f where f.followed = :user"