如何使用jpa/hibernate连接fetch两个关联

dnph8jn4  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(349)

我刚开始冬眠,真的需要你们的帮助。。。。我有以下类: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是一个表,对于电子邮件消息,还有一个名为useractionperuserresultemailmessage的表,该表将电子邮件消息与表useractionperuserresult的id相关联。
我将所有数据存储在mysql表中,但是我无法查询它。我需要写一个查询来获取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();
hl0ma9xz

hl0ma9xz1#

尝试这样编写查询:

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

联接正在使用根实体别名
当与数值匹配时,useraction.id用于useraction

相关问题