实体内的原始查询

时间:2018-04-05 16:44:57

标签: java hibernate jpa kotlin

我正在制作推特克隆。

联接表会创建一个following表,其中包含user_idfollower_id

@ManyToMany(fetch = FetchType.EAGER, cascade = [CascadeType.PERSIST])
@JoinTable(
        name = "following",
        joinColumns = [(JoinColumn(name = "user_id", referencedColumnName = "id"))],
        inverseJoinColumns = [(JoinColumn(name = "follower_id", referencedColumnName = "id"))]
)
var following: List<User> = emptyList()

以下查询为我提供了关注者

SELECT * FROM users WHERE id = (SELECT user_id FROM following WHERE `follower_id` = 1)

如何在我的实体中实现此查询?

1 个答案:

答案 0 :(得分:-1)

查看ManyToMany上的mappedBy属性。 https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/ManyToMany.html 您可以向实体类添加一个额外的字段,以完成您要查找的内容。

@ManyToMany(mappedBy = "following")
var followers: List<User> = emptyList()