本文介绍了当关系相反时,如何使用CriteriaBuilder编写左外部联接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用JPA 2.0,Hibernate 4.1.0.Final和MySQL 5.5.37.我有以下两个实体...
I’m using JPA 2.0, Hibernate 4.1.0.Final and MySQL 5.5.37. I have the following two entities …
@Entity
@Table(name = "msg")
public class Message
{
@Id
@NotNull
@GeneratedValue(generator = "uuid-strategy")
@Column(name = "ID")
private String id;
@Column(name = "MESSAGE", columnDefinition="LONGTEXT")
private String message;
和
@Entity
@Table(name = "msg_read", uniqueConstraints = { @UniqueConstraint(columnNames = { "MESSAGE_ID", "RECIPIENT" }) })
public class MessageReadDate
{
@Id
@NotNull
@GeneratedValue(generator = "uuid-strategy")
@Column(name = "ID")
private String id;
@ManyToOne
@JoinColumn(name = "RECIPIENT", nullable = false, updatable = true)
private User recipient;
@ManyToOne
@JoinColumn(name = "MESSAGE_ID", nullable = false, updatable = true)
private Message message;
@Column(name = "READ_DATE")
private java.util.Date readDate;
使用CriteriaBuilder,我该怎么写
Using CriteriaBuilder, how would I write this
SELECT DISTINCT m.*
FROM msg AS m
LEFT JOIN msg_read AS mr
ON mr.message_id = m.id AND mr.recipient = 'USER1'
?我的问题是我的Message实体中没有字段"msg_read",而且我不确定如何在CriteriaBuilder中指定左外部联接的"AND"部分.
? My problem is that there is no field "msg_read" in my Message entity, and I’m not sure how to specify the "AND" part of the left outer join in CriteriaBuilder.
推荐答案
您可以执行以下操作.
final Root<Message> messageRoot = criteriaQuery.from(Message.class);
Join<Message, MessageReadDate> join1 = messageRoot .join("joinColumnName", JoinType.LEFT);
Predicate predicate = criteriaBuilder.equal(MessageReadDate.<String> get("recipient"), recepientValue;
criteria.add(predicate);
criteriaQuery.where(predicate);
criteriaQuery.distinct(true);
我希望这能解决您的查询.
I hope this will resolve your query.
这篇关于当关系相反时,如何使用CriteriaBuilder编写左外部联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!