java-如何通过JPA / Hibernate加入获取两个关联
作者:互联网
我是Hibernate的新手,确实需要你们的帮助.
我有以下课程: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
标签:jpa,hibernate,hibernate-mapping,java,mysql 来源: https://codeday.me/bug/20191120/2043768.html