gpt4 book ai didi

java - JPA 条件查询 - 如何避免重复连接

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:58:26 24 4
gpt4 key购买 nike

我需要使用大量条件连接和 where 子句进行条件查询,在这种情况下,代码往往会变得复杂并且可能会产生重复连接。

例如,我有以下表结构和 JPA 实体:

ACCOUNT
ACCOUNT_ID
ACCOUNT_TYPE


PERSON
NAME
AGE
ACCOUNT_ID ( FK TO ACCOUNT )
ADDRESS_ID ( FK TO ADDRESS )

ADDRESS
ADDRESS_ID
LOCATION
COUNTRY

因此假设我使用静态元模型实现来应用条件查询。

这是可以生成重复连接的错误代码示例:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);

cq.select(accountRoot).where(
cb.and(
cb.equal(accountRoot.join(Account_.person).get(Person_.name),"Roger"),
cb.greaterThan(accountRoot.join(Account_.person).get(Person_.age),18),
cb.equal(accountRoot.join(Account_.person)
.join(Person_.address).get(Address_.country),"United States")
)
)

TypedQuery<Account> query = entityManager.createQuery(cq);
List<Account> result = query.getResultList();

上面的代码将生成一个包含同一个表的多个连接的 SQL:

 Select
account0_.account_id as account1_2_,
account0_.account_type as account2_2_
from
account account0_
inner join
person person1_
on account0_.account_id=person1_.account_id
inner join
address address2_
on person1_.address_id=address2_.address_id
inner join
person person3_
on account0_.account_id=person3_.account_id
inner join
person person4_
on account0_.account_id=person4_.account_id
inner join
person person5_
on account0_.account_id=person5_.account_id
inner join
address address6_
on person5_.address_id=address6_.address_id
where
person3_.name=?
and person4_.age>18
and address6_.country=?

一个简单的解决方案是保留 Join 的实例以在多个谓词中重复使用:

   Root<Account> accountRoot = cq.from(Account.class);
Join<Account,Person> personJoin= accountRoot.join(Account_.person);
Join<Person,Address> personAddressJoin = accountRoot.join(Person_.address);

cq.select(accountRoot).where(
cb.and(
cb.equal(personJoin.get(Person_.name),"Roger"),
cb.greaterThan(personJoin.get(Person_.age),18),
cb.equal(personAddressJoin.get(Address_.country),"United States")
)
)

好的,它可以工作,但是对于具有多个表和代码的条件连接的真正复杂代码,往往会变成意大利面条代码!相信我 !

避免它的更好方法是什么?

最佳答案

我们使用以下实用方法来避免重复连接

public class CriteriaApiUtils {
public static <X, Y> ListJoin<X, Y> join(Root<X> criteriaRoot,
ListAttribute<? super X, Y> attribute,
JoinType joinType
) {
return (ListJoin<X, Y>) criteriaRoot.getJoins().stream()
.filter(j -> j.getAttribute().getName().equals(attribute.getName()) && j.getJoinType().equals(joinType))
.findFirst()
.orElseGet(() -> criteriaRoot.join(attribute, joinType));
}
}

关于java - JPA 条件查询 - 如何避免重复连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com