gpt4 book ai didi

java - Spring Data JPARepository : How to conditionally fetch children entites

转载 作者:IT老高 更新时间:2023-10-28 13:47:35 25 4
gpt4 key购买 nike

除非提供了某个执行参数,否则如何配置他们的 JPA 实体以不获取相关实体。

根据 Spring 的文档,4.3.9. Configuring Fetch- and LoadGraphs ,您需要使用 @EntityGraph 注释来指定查询的获取策略,但这并不能让我在运行时决定是否要加载这些实体。

我可以在单独的查询中获取子实体,但为了做到这一点,我需要将我的存储库或实体配置为不检索任何子实体。不幸的是,我似乎找不到任何关于如何做到这一点的策略。 FetchPolicy 被忽略,EntityGraph 仅在指定我想要急切检索的实体时才有用。

例如,假设 Account 是父级,Contact 是子级,并且一个 Account 可以有多个联系人。

我希望能够做到这一点:

if(fetchPolicy.contains("contacts")){
account.setContacts(contactRepository.findByAccountId(account.getAccountId());
}

问题是 spring-data 无论如何都急切地获取联系人。

Account Entity 类如下所示:

@Entity
@Table(name = "accounts")
public class Account
{
protected String accountId;
protected Collection<Contact> contacts;

@OneToMany
//@OneToMany(fetch=FetchType.LAZY) --> doesn't work, Spring Repositories ignore this
@JoinColumn(name="account_id", referencedColumnName="account_id")
public Collection<Contact> getContacts()
{
return contacts;
}

//getters & setters

}

AccountRepository 类如下所示:

public interface AccountRepository extends JpaRepository<Account, String>
{
//@EntityGraph ... <-- has type= LOAD or FETCH, but neither can help me prevent retrieval
Account findOne(String id);
}

最佳答案

如果没有调用 getContacts() 产生的对象方法,则延迟获取应该正常工作。

如果您喜欢更多的手动工作,并且真的希望对此进行控制(可能更多的上下文取决于用例)。我建议您从帐户实体中删除联系人,然后将帐户映射到联系人中。告诉 hibernate 忽略该字段的一种方法是使用 @Transient 注释对其进行映射。

@Entity
@Table(name = "accounts")
public class Account
{
protected String accountId;
protected Collection<Contact> contacts;

@Transient
public Collection<Contact> getContacts()
{
return contacts;
}

//getters & setters

}

然后在您的服务类中,您可以执行以下操作:

public Account getAccountById(int accountId, Set<String> fetchPolicy) {
Account account = accountRepository.findOne(accountId);
if(fetchPolicy.contains("contacts")){
account.setContacts(contactRepository.findByAccountId(account.getAccountId());
}
return account;
}

希望这是您正在寻找的。顺便说一句,代码未经测试,因此您可能应该再次检查。

关于java - Spring Data JPARepository : How to conditionally fetch children entites,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33266952/

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