我将hibernate 5.2.10与动态条件一起使用,发现fetch不再可分配给join。
在下一个示例中,我需要在同一个查询中获取组数据,但也需要使用组的字段进行排序或限制。

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<GroupAssignment> query = cb.createQuery(GroupAssignment.class);

Root<GroupAssignment> root = query.from(GroupAssignment.class);
SingularAttributeJoin<GroupAssignment, Group> groupFetch = (SingularAttributeJoin<GroupAssignment, Group>) root.fetch(GroupAssignment_.group, JoinType.LEFT);
query.orderBy(cb.asc(groupFetch.get(Group_.title)));

我已经手动将fetch转换为singularattributejoin,然后,我可以使用get方法进行排序,但是我正在寻找一种正确的方法,不需要手动转换就可以做到这一点。
组分配类:
@Entity()
@Table(name = "group_assignment")
public class GroupAssignment {
  @Id
  @Column(name = "group_assignment_id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @ManyToOne
  @JoinColumn(name = "group_id", nullable = false)
  private Group group;

  //other fields, getters and setters
}

分组作业类别:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(GroupAssignment.class)
public abstract class GroupAssignment_ {
  public static volatile SingularAttribute<GroupAssignment, Integer> id;
  public static volatile SingularAttribute<GroupAssignment, Group> group;
}

组别:
@Entity()
@Table(name = "navigation_group")
public class Group {
  @Id
  @Column(name = "group_id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name = "title")
  private String title;

  //other fields, getters and setters
}

组别:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Group.class)
public abstract class Group_ {
  public static volatile SingularAttribute<Group, Integer> id;
  public static volatile SingularAttribute<Group, String> title;
}

最佳答案

我认为javax.persistence.criteria.fetchparent可以解决您的问题:

FetchParent<GroupAssignment, Group> groupFetch = root.fetch(GroupAssignment_.group, JoinType.LEFT);

07-28 05:00