如何使用 JPA/Hibernate 加入获取两个关联

How to join fetch two associations with JPA/Hibernate

我是 Hibernate 的新手,真的需要你们的帮助.... 我有以下 class:UserActionPerUserResult

@Entity
@Table(name = "user_action_per_user_result")
public class UserActionPerUserResult {

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

    @Column(name = "user_email", nullable = false)
    private String userEmail;

    @ManyToOne
    @JoinColumn(name = "user_action_id", nullable = false)
    private UserAction userAction;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name="user_action_per_user_result_email_message",
                  joinColumns={@JoinColumn(name="user_action_per_user_result_id", referencedColumnName="id")},
                  inverseJoinColumns={@JoinColumn(name="email_message_id", referencedColumnName="id")})
    @JsonIgnore
    private List<EmailMessage> emailMessages;

....getters/setter....
}

在 MYSQL 中,UserActionPerUserResult 是一个 table,对于电子邮件消息,还有另一个 table 称为 UserActionPerUserResultEmailMessage,它具有与 [=22= 的 ID 关联的电子邮件消息] UserActionPerUserResult.

我将所有数据都存储在 MySQL table 中,但是我无法查询它。我需要编写一个查询来获取 emailMessages 列表。我正在尝试以下操作,但它抛出异常。

TypedQuery<UserActionPerUserResult> messagesQuery =     entityManager.createQuery(
                    "SELECT e from UserActionPerUserResult e JOIN UserActionPerUserResult.emailMessages e1 WHERE e.id = 1 and e.userAction = 1", UserActionPerUserResult.class);
List<UserActionPerUserResult> resultList = messagesQuery.getResultList();

尝试像这样编写查询:

TypedQuery<UserActionPerUserResult> messagesQuery = entityManager.createQuery(
   "SELECT e from UserActionPerUserResult e JOIN FETCH e.emailMessages em WHERE e.id = 1 and e.userAction.id = 1", UserActionPerUserResult.class);
List<UserActionPerUserResult> resultList = messagesQuery.getResultList();
  1. 连接正在使用根实体别名
  2. userAction.id 用于 userAction,匹配数值