如何使用JPA规范在非主键列上创建查询

huangapple go评论117阅读模式
英文:

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&lt;User&gt; userAndDetails(Long userKey) {
		return (Root&lt;User&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder builder) -&gt; {
		
			Root&lt;UserDetails&gt; 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);
		};
	}

huangapple
  • 本文由 发表于 2020年8月19日 13:49:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63480756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定