【发布时间】:2016-01-20 21:37:43
【问题描述】:
除非提供了某个执行参数,否则如何配置他们的 JPA 实体以不获取相关实体。
根据 Spring 的文档 4.3.9. Configuring Fetch- and LoadGraphs,您需要使用 @EntityGraph 注释来指定查询的获取策略,但这并不能让我在运行时决定是否要加载这些实体。
我可以在单独的查询中获取子实体,但为了做到这一点,我需要将我的存储库或实体配置为不检索任何子实体。不幸的是,我似乎找不到任何关于如何做到这一点的策略。 FetchPolicy 被忽略,EntityGraph 仅在指定我想要急切检索的实体时才有用。
例如,假设Account 是父级,Contact 是子级,并且一个帐户可以有多个联系人。
我希望能够做到这一点:
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);
}
【问题讨论】:
-
JPA 中的集合默认是惰性的,Spring Data JPA 对此没有任何改变。如果在您的代码中某处调用了
getContacts,那么所有内容都将被获取,因为这是默认设置。
标签: java spring hibernate spring-mvc jpa