JPA很多人质疑

时间:2015-08-25 21:02:56

标签: java hibernate jpa jpa-2.0 criteria

我有这个课程:

ChatRoom类:

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

用户类:

@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;
}

ChatRoomMessage类:

@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();
    }
}

如果我想要用户发送的所有消息,我都是在DAO:

MessagesDAO类:

ngTagsInput

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

  1. 获取用户发送或接收的所有聊天室消息。
  2. 获取用户在聊天室发送或接收的所有聊天室消息。
  3. 您能否就如何解决疑问提出想法?

1 个答案:

答案 0 :(得分:0)

您可以按如下方式编写查询:

第一次查询:

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();

希望这能解决你的问题。