[英]How to create query using JPA specification on non primary column
I have the below query, where two tables are joining on non primary column.我有以下查询,其中两个表在非主列上加入。 The table is joining on one common column.该表正在连接一个公共列。
In entity, I have not provided any joining between User and UserDetails, and I don't want to provide either在实体中,我没有提供用户和用户详细信息之间的任何连接,我也不想提供
SELECT * from User user, UserDetails ud
WHERE user.user_key = :pUserKey // passed in parameter
user.common_key = ud.common_key
User用户
@Entity
@Table(name = "USER")
@Data
public class User implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "user_key", nullable = false)
@JsonIgnore
private Long userKey;
@Column(name = "common_key ", nullable = false)
@JsonIgnore
private Long commonKey;
}
UserDetails用户详情
@Entity
@Table(name = "USER_DETAILS")
@Data
public class UserDetails implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "user_details_key", nullable = false)
@JsonIgnore
private Long userDetailsKey;
@Column(name = "common_key ", nullable = false)
@JsonIgnore
private Long commonKey;
}
How to achieve the same query in JPA specification如何在 JPA 规范中实现相同的查询
I have got the solution as expected.我已经得到了预期的解决方案。 I have created new root
using query.from()
我使用query.from()
创建了新的root
Below is the complete solution下面是完整的解决方案
public static Specification<User> userAndDetails(Long userKey) {
return (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> {
Root<UserDetails> userDetailsRoot = query.from(UserDetails.class);
Predicate userAndDetailsJoin = builder.equal(
root.get(User_.commonKey),
userDetailsRoot.get(UserDetails_.commonKey));
Predicate userKeyPredicate = builder.equal(root.get(User_.userKey),
userKey);
return builder.and(userAndDetailsJoin, userKeyPredicate);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.