UserActionPerUserResult

UserActionPerUserResult

我是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是一个表,对于电子邮件消息,还有另一个名为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();

最佳答案

尝试像这样编写查询:

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

    关于java - 如何通过JPA/Hibernate加入获取两个关联,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29908411/

    10-10 10:29