I'm using Hibernate 5.2.10 with dynamic criteria and find out that Fetch is not longer assignable to Join.
In the next example, I need to fetch group data in the same query, but I also need to use the group's field for sorting or restriction.
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)));
I have manually cast Fetch to the SingularAttributeJoin and after that, I can use get method for the ordering purpose, but I'm looking for the right way how I can do that without casting manually .
GroupAssignment class:
@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
}
GroupAssignment_ class:
@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;
}
Group class:
@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
}
Group_ class:
@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);
It appears that correct way would be next:
query.orderBy(cb.asc(root.get(GroupAssignment_.group).get(Group_.title)));
So using multiple call to .get
method you can go as deep as needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.