JPA Criteria multiselect with fetch - java.lang.IllegalArgumentException:org.hibernate.QueryException

g6baxovj  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(131)

我有以下模型,并努力从我的查询中检索结果:

@Entity
public class MyData {

    @Id
    private String id;

    @Column(name = "security_id")
    private Long securityId;

    @Version
    private Long version;

    @OneToOne
    @JoinColumn(name = "id", referencedColumnName = "id")
    private MyDataDetails myDataDetails;

    MyData() {
    }

//other fields here
//omitted getters/setters
}

@Entity
public class MyDataDetails {

    @Id
    private String id;

    @Version
    private Long version;

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

    @Column(name = "created_on")
    private LocalDateTime createdOn;

    MyDataDetails() {
    }
//other fields here
//omitted getters/setters
}

字符串
现在我只想查询列:id,securityId和引用MyDataDetails实体的myDataDetails(不是完整的实体,因为它有许多其他属性,我想有最好的性能)。
当我写query时:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Tuple> query = builder.createTupleQuery();
    Root<MyData> root = query.from(MyData.class);
    ///query.select(root).distinct(true);
    root.fetch(MyDataDetail_.myDataDetails, JoinType.LEFT);
     query.distinct(true).multiselect(
                root.get(MyDataDetail_.id),
                root.get(MyDataDetail_.securityId), root.get(MyDataDetail_.myDataDetails));
  entityManager.createQuery(query).getResultList().stream()
                .map(tuple -> new MyDto(tuple.get(0, String.class), null, null, null, null, null, null, null, null,
                        null, null, null, 0, tuple.get(13, MyDataDetails.class)))
                .collect(Collectors.toList());


我有以下例外:
原因:java.lang.IllegalArgumentException:org.hibernate.QueryException:查询指定了连接获取,但获取的关联的所有者不在选择列表中[FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,className = generatedAlias 1,role=MyData.myDataDetails,tableName=,tableName = da1_,origin =*,columns={0.id,className=MyDataDetails}}] [select distinct generatedAlias0.id,generatedAlias0.securityId,generatedAlias0.myDataDetails from MyData as generatedAlias0 left join fetch generatedAlias0.myDataDetails as generatedAlias1 where((1=1)and(generatedAlias0.owningAuthority=:param0))and(1=1)]

wqsoz72f

wqsoz72f1#

为了让fetch工作,你必须返回完整的所有者实体。例如,像这样:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery< MyData > query = builder.createQuery(MyData.class);
Root<MyData> root = query.from(MyData.class);

root.fetch(MyDataDetail_.myDataDetails, JoinType.LEFT);
query.distinct(true).select(root);
  entityManager.createQuery(query).getResultList().stream()
                .map(e -> new MyDto(e.getId(), null, null, null, null, null, null, null, null,
                        null, null, null, 0, e.getMyDataDetails()))
                .collect(Collectors.toList());

字符串

相关问题