【问题标题】:JPA Query ElementCollection keyJPA 查询 ElementCollection 键
【发布时间】:2015-10-13 11:12:08
【问题描述】:

我有一个名为 User 的实体类,其变量 username 和 ElementCollection 映射表示两个用户之间的“友谊”,由 userId、开始日期和朋友的 id 映射。该关系的代码如下:

@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "friendship", joinColumns = @JoinColumn(name="userId"))
@MapKeyColumn(name = "friendId")
@Column(name = "startDate")
private Map<Integer, Date> friendShipMap;

我想在每个用户的个人资料页面上显示朋友。我知道我可以通过 Java 访问地图并获取 ID(并找到这样的朋友的用户名),但我想使用自定义 @Query 来获取给定 ID 的所有朋友用户名。不知何故,这张地图让我很困惑,我找不到合适的说法。

非常感谢您对此的任何帮助。

编辑:澄清一下,我想为以下 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

【问题讨论】:

  • 你能展示一些你尝试过的语句的代码吗?
  • 大部分都删除了,但我基本上需要的是相当于“select u.username from users u joinfriendship m on u.userId = m.friendId where m.userId = 1;”跨度>

标签: java jpa


【解决方案1】:

你可以使用这个@Query

@Query("select u.username from Users u inner join u.friendship f where f.friendId = :userId")

确保您的实体 UsersFriendship 之间有一个 association。我认为应该是@OneToMany 关系。

而且它应该是List&lt;String&gt; 而不是Map

编辑:1

如果我理解正确,您将需要另一个课程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

【讨论】:

  • 我从stackoverflow.com/questions/20663704/… 获得了代码,其中的地图(id,日期)表示这种关系的开始日期。问题是,我要么没有从查询中得到任何结果,要么(使用您的查询)它是 org.hibernate.QueryException: cannot dereference scalar collection element:friendId
  • 刚刚编辑了我的原始帖子,显示了一个不起作用的示例查询。地图本身不包含userId,而是包含friendId,因此我不能这样引用它。我不确定如何从这段代码继续
  • 只有两个类真正值得一提。用户实体类有一个 id (userId)、用户名和 @ElementCollectionfriendShipMap。另一个是我的接口扩展了一个 JpaRepository ,它提供了我的自定义查询。两者都在我的原始帖子中提供。没有实体类本身代表友谊,因为这就是我使用集合表的目的。
  • 希望通过查询来解决这个问题,但从长远来看,最终创建一个单独的实体可能是最好的主意。感谢您的宝贵时间
  • 我不确定是否有不创建新实体的解决方案。但无论如何,一个新类使您的代码也更具可读性和结构化。我认为你不会犯这种方法的错误。
猜你喜欢
  • 2013-01-21
  • 2021-02-17
  • 2018-01-13
  • 2017-05-22
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 2014-01-12
  • 2020-07-04
相关资源
最近更新 更多