英文:
How to create query using JPA specification on non primary column
问题
以下是翻译好的部分:
我有以下查询,其中两个表在非主键列上进行连接。表格通过一个共同的列进行连接。
在实体中,我没有提供User和UserDetails之间的连接,并且我也不想提供。
如何在JPA规范中实现相同的查询?
英文:
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
答案1
得分: 1
我已按预期获得了解决方案。我使用query.from()
创建了新的root
。
以下是完整的解决方案:
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);
};
}
英文:
I have got the solution as expected. I have created new root
using query.from()
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);
};
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论