我有一个名为 User 的实体类,其中包含变量 username 和 ElementCollection 映射来表示两个用户之间的“友谊”,由 userId、开始日期和 friend 的 id 映射。该关系的代码如下:
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "friendship", joinColumns = @JoinColumn(name="userId"))
@MapKeyColumn(name = "friendId")
@Column(name = "startDate")
private Map<Integer, Date> friendShipMap;
我想在每个用户的个人资料页面上显示 friend 。我知道我可以通过 Java 访问 map 并获取 id(并找到这样的 friend 的用户名),但我想使用自定义 @Query 来获取给定 id 的所有 friend 用户名。不知何故, map 让我感到困惑,我找不到合适的说法。
非常感谢对此的任何帮助。
编辑:为了澄清,我想对以下 SQL 语句使用自定义 @Query 语句:
select u.username from users u join friendship m on u.userId = m.friendId where m.userId = 1;
所以我认为它基本上是这样的:
@Query("SELECT u.username FROM users u join u.friendShipMap m on u.userId = key(m) where m.userId = :userId")
List<User> getFriends(@Param("userId") int userId);
但我不能使用 m.userId,它说“无法取消引用标量集合元素:userId”。
对应的表格如下所示:
userId | startDate |friendId
最佳答案
您可以使用这个@Query
@Query("select u.username from Users u inner join u.friendship f where f.friendId = :userId")
确保您有 association
您的实体之间Users
和Friendship
。应该是@OneToMany
我认为有关系。
它应该在 List<String>
中而不是Map
.
编辑:1
如果我理解正确的话,你将需要另一个类(class) friendship
.
也许您需要此处描述的可嵌入类( friendship
)。
http://www.thejavageek.com/2014/01/31/jpa-elementcollection-annotation/
或者您可以创建一个新实体。
http://www.concretepage.com/hibernate/elementcollection_hibernate_annotation
这也是一个很好的例子:
https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
关于java - JPA 查询 ElementCollection 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33101168/