Hibernate查询获取对象列表,每个需要的对象都在其他对象列表内.列表是另一个对象的一部分 &g



我从早上开始就在努力查询。我有以下JSON:

{
"id": "87ee51c7-3f15-4772-a2fb-bee379e1054d",
"description": "What color do you like?",
"option1": "Yellow",
"option2": "Blue",
"option3": "Green",
"option4": "Red",
"option5": "Pink",
"votes": [
{
"id": "26bf4e30-c75a-4267-8850-4f04101fdd35",
"answerOption": "Pink",
"user": {
"id": "f836bd80-53d8-4623-8198-ca375abfdbbc",
"authId": "auth0|5ff8fe4bee9af4febf00762c3f1e",
"firstName": "Test",
"lastName": "Name",
"phone": "07545166181",
"email": "user@yahoo.com",
"buildingStreet": "test",
"buildingNumber": "15",
"buildingName": "8",
"buildingEntrance": "A",
"town": "town",
"country": "country",
"other": ""
},
"date": "2021-01-30"
},
{
"id": "0047474f-ecf1-424b-960a-a512e6bb14f5",
"answerOption": "Blue",
"user": {
"id": "7da77dff-a22a-47ac-b995-41fa90866016",
"authId": "auth0|60055f048ec4a3006ee36d64",
"firstName": "John",
"lastName": "Doe",
"phone": "0755888999",
"email": "user2@yahoo.com",
"buildingStreet": "street",
"buildingNumber": "15",
"buildingName": "8",
"buildingEntrance": "A",
"town": "town",
"country": "country",
"other": ""
},
"date": "2021-01-30"
}
],
"status": "active",
"endDate": "2021-02-05"
}

所以我有一个投票,有id,描述和5个投票选项。投票有一个投票列表,所以我有多个投票。每个投票包含一个答案,日期和用户。

是否有一个查询来建立一个知道问题id的用户列表?

这个想法是建立这个已经投票的用户列表,所以我限制他们在同一个投票中投票两次。

我使用Hibernate作为ORM, Spring Boot用于后端,React用于前端。

findAllUsers列表…

是否有一种方法可以用语句到达那里?最近我在使用Hibernate,我对手工查询非常生疏。

提前谢谢你

假设数据结构如下:

public class User {
@Id private Long id;

// getters & setters
}
public class Vote {
@Id private Long id;

@ManyToOne private Poll poll;

@ManyToOne private User user;

// getters & setters
}
public class Poll {
@OneToMany List<Vote> votes;

// getters & setters

}

使用存储库,我认为最干净的地方应该是VoteRepository。为此,存储库应该是这样的(使用带有方法名的查询生成,请参阅Spring Data JPA参考指南中的查询方法):

public interface VoteRepository extends JpaRepository<Vote> {
List<Vote> findByPoll(Poll poll);
}

然后,要获得与投票相关的所有用户,例如在控制器中,应该完成从投票到用户的映射:

@Autowired
VoteRepository voteRepository;
public List<User> getUsersRelatedToPoll(Poll poll) {
List<Vote> votes = voteRepository.findByPoll(poll);
return votes.stream().map(Vote::getUser).collect(Collectors.toList());
}

另一种方式,恕我直言不是最干净的方式(^1),可以是@Query方法(参见在Spring Data JPA参考指南中使用@Query)。这个方法看起来像这样:

public interface FooRepository extends JpaRepository<Foo> {
@Query("SELECT v.user FROM VOTE as v WHERE v.poll = :poll")
List<User> findUsersByPoll(@Param("poll") Poll poll);
}

^1:我认为,例如在UserRepository不应该知道或使用PollVote

最新更新