我们有一个媒体对象:
public class Media implements Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(insertable = false, updatable = false)
private Long id;
// other attributes
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "channelId", referencedColumnName = "id")
private Channel channel;
// getters, setters, hashCode, equals, etc.
channel 父级的急切获取在常规存储库方法中有效,但在使用规范时无效。
这是规范:
public class MediaSpecs {
public static Specification<Media> search(final Long partnerId, final Integer width, final Integer height,
final String channelType) {
return new Specification<Media>() {
@Override
public Predicate toPredicate(Root<Media> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate restrictions = cb.equal(root.get("archived"), false);
// other restrictions are and-ed together
if (channelType != null) {
Join<Media, ChannelType> join = root.join("channel").join("orgChannelType").join("type");
restrictions = cb.and(cb.equal(join.get("type"), channelType));
}
return restrictions;
}
};
}
“搜索”规范在指定 channelType 时工作正常,因此连接工作正常。如何指定应急切获取连接?
我尝试添加
Fetch<Media, ChannelType> fetch = root.fetch("channel").fetch("orgChannelType").fetch("type");
然后 Hibernate 抛出一个异常:
org.hibernate.QueryException: query specified join fetching, 但获取关联的所有者不在选择列表中...
如何将关联添加到选择列表?
谢谢。
最佳答案
我认为您对计数查询有疑问。通常该规范用于数据查询和计数查询。对于计数查询,没有“媒体”。我使用这个解决方法:
Class<?> clazz = query.getResultType();
if (clazz.equals(Media.class)) {
root.fetch("channel");
}
这仅将 fetch 用于数据查询而不用于计数查询。
关于java - 在 Spring 规范中渴望获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27909100/