在我的春季启动项目中,我有一个定义的聊天和用户实体,它们由多对多
相关联Chat.java
@ManyToMany
@JoinTable(name = "chat_user",
joinColumns = @JoinColumn(name = "chat_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
private Set<User> users = new HashSet<User>();
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
User.java
@ManyToMany
@JsonBackReference
@JoinTable(name = "chat_user",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "chat_id", referencedColumnName = "id"))
private Set<Chat> chats = new HashSet<Chat>();
public Set<Chat> getChats() {
return chats;
}
public void setChats(Set<Chat> chats) {
this.chats = chats;
}
如何在CrudRepository中编写方法,以便从用户列表中获得包含所有用户的聊天列表
到目前为止,我有一个书面方法可以返回一个聊天列表,其中包含用户列表中任意的用户
public interface ChatRepo extends CrudRepository<Chat, Long> {
List<Chat> findAllByUsers(User user);
List<Chat> findDistinctByUsersIn(Set<User> users);
}
答案 0 :(得分:0)
没有直接的解决方案(从我看到的)。你能做的是什么 像你这样在你的ChatRepo中创建一个方法
public interface ChatRepository extends CrudRepository<Chat, Long> {
@Query("select c from Chat c WHERE :user in elements(c.users)")
List<Chat> getChatsWithUsers(@Param("user") User user);
}
这将为您提供此特定用户所参与的所有聊天的结果。
然后,您可以为集合中的所有用户执行此操作,然后执行结果的交集
为此,您需要将@ElementCollection
放入聊天类
..........
@ElementCollection
private Set<User> users = new HashSet<User>();
但我同意这不是一个理想的解决方案,因为如果列表太大,那么它会导致多个数据库调用
答案 1 :(得分:0)
@ManyToMany
@JoinTable(name = "chat_user",
joinColumns = @JoinColumn(name = "chat_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName =
"id"))
private Set<User> users = new HashSet<User>();
I think this is maybe wrong. Because one chat id cannot point out many user.
So you can use simple jointable to user entity
答案 2 :(得分:0)
实现equals / hashCode就像Malte Hartwig建议的那样是解决方案
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof User)) {
return false;
}
User user = (User) o;
return id == user.id &&
Objects.equals(firstName, user.firstName) &&
Objects.equals(lastName, user.lastName) &&
Objects.equals(userName, user.userName) &&
Objects.equals(password, user.password);
}
@Override
public int hashCode() {
return Objects.hash(id, firstName, lastName, userName, password);
}