Eri*_*ric 8 java spring jpa spring-data-jpa
我们有一个Media对象:
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.
Run Code Online (Sandbox Code Playgroud)
}
对通道父级的急切提取在常规存储库方法中工作,但在使用规范时则不行.
这是规格:
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;
}
};
}
Run Code Online (Sandbox Code Playgroud)
指定channelType时,"搜索"规范正常工作,因此连接正常.如何指定应该热切地获取连接?
我尝试添加
Fetch<Media, ChannelType> fetch = root.fetch("channel").fetch("orgChannelType").fetch("type");
Run Code Online (Sandbox Code Playgroud)
然后Hibernate抛出异常:
org.hibernate.QueryException:查询指定的连接获取,但是获取的关联的所有者在选择列表中不存在[FromElement {显式,不是集合连接,获取连接,获取非延迟属性,classAlias = generatedAlias4 ...
如何将关联添加到选择列表?
谢谢.
小智 12
我认为你有计数查询的问题.通常该规范用于数据查询和计数查询.而对于计数查询,没有"媒体".我用这个解决方法:
Class<?> clazz = query.getResultType();
if (clazz.equals(Media.class)) {
root.fetch("channel");
}
Run Code Online (Sandbox Code Playgroud)
这仅用于数据查询,而不用于计数查询.
例如:
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
if (Long.class != query.getResultType()) {
root.fetch(Person_.addresses);
}
return cb.conjunction();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1980 次 |
| 最近记录: |