簡體   English   中英

休眠條件:dto作為實體

[英]Hibernate criteria: dto as entity

我有一個使用Hibernate Criteria構建的查詢(我僅向您顯示“主要”部分):

Criteria criteria = sessionProvider.get().createCriteria(User.class);
// Add other stuff to the query like joins, group-bys, order-bys etc.
// In the projection list add the "id" of the user.
projectionList.add(Projections.property("id"), "id");
// finally using same entity class User as dto
criteria.setResultTransformer(Transformers.aliasToBean(User.class));

所以我終於可以做:

List<User> users = criteria.list();

當我嘗試從該實體加載值時,問題就來了。 例如:

users.get(0).getFirstName();

返回null。 因此,基本上,由Transformers.aliasToBean創建的像“ dtos”這樣的實體通過投影僅接收到“ id”,這些實體不能用作由get / load / etc加載的普通實體。

有什么方法可以使這些dto作為實體“工作”?

似乎在projectionList中傳遞參數是錯誤的,您需要像這樣修改projectionList。

Criteria criteria = sessionProvider.get().createCriteria(User.class);
//Add other stuff to the query like joins, group-bys, order-bys etc.

//In the projection list add the columns name which are mapped with the entity
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("id"));
projectionList.add(Projections.property("firstName"));
criteria.setProjection(projectionList);

List<User> results = criteria.list();

//output results
for(User user : results) {
    user.getFirstName();        
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM