gpt4 book ai didi

java - JPA 多对多查询

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:58 25 4
gpt4 key购买 nike

我有这样的类(class):

ChatRoom 类:

@Entity
public class ChatRoom {

@Column(name="chatroom_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long chatroomId;

@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="CHATROOM_USER",
joinColumns = {@JoinColumn(name="chatroom_id",referencedColumnName="chatroom_id")},
inverseJoinColumns={@JoinColumn(name="user_id",referencedColumnName="user_id")}
)
private Set<User> users;

@OneToMany(mappedBy="chatroom", cascade=CascadeType.PERSIST, orphanRemoval=true)
private Set<ChatRoomMessage> messages;
}

用户类别:

@Entity
public class User {
@Id
@Column(name="user_id", length=40, unique=true, updatable=false)
private String userId;
}

ChatRoomMessage 类:

@Entity
public class ChatRoomMessage {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long messageId;

@ManyToOne(optional=false)
@JoinColumn(name="session_id", nullable=false)
private User sender;

@ManyToOne(optional=false)
@JoinColumn(name="chatroom_id", nullable=true)
private ChatRoom chatroom;
}

如果我想要用户发送的所有消息,我在 DAO 上做了这个:

MessagesDAO 类:

@Repository
public class MessageDaoImpl implements MessageDaoI {
@Override
public List<ChatRoomMessage> getMessages(User u){
Criteria c = sessionFactory.getCurrentSession().createCriteria(ChatRoomMessage.class, "cmessage");
c.createAlias("cmessage.sender", "sender");
c.add(Restrictions.eq("sender", u));
return c.list();
}
}

当我尝试编写下一个查询时,问题就开始了:

  1. 获取用户发送或接收的所有聊天室消息。
  2. 获取用户在聊天室发送或接收的所有聊天室消息。

您能否提供有关如何解决疑问的想法?

最佳答案

您可以编写如下查询:

第一个查询:

Query query = session.createQuery("from ChatRoomMessage as c JOIN c.sender where c.sender.userId = :senderUserId");
query.setString("senderUserId", "SENDER_USER_ID_TO_BE_SEARCHED");
List list = query.list();

第二个查询:

Query query = session.createQuery("from ChatRoomMessage as c JOIN fetch c.chatroom where c.chatroom.users.userId = :senderUserId");
query.setString("senderUserId", "SENDER_USER_ID_TO_BE_SEARCHED");
List list = query.list();

希望这能解决您的问题。

关于java - JPA 多对多查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32214022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com