我正在使用JPA 2.0,Hibernate 4.1.0.Final和MySQL 5.5.37。我有以下两个实体...
@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,我该怎么写
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”部分。
最佳答案
你可以做这样的事情。
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);
希望这可以解决您的查询。
关于jpa - 当关系相反时,如何使用CriteriaBuilder编写左外部联接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25788965/