[英]“select new constructor” query returns java.lang.Object instead of instance of constructors class
var toShow
is instance of pure java.lang.Object
, and the only way it works if I cast it to FactionProjection
, and I do not think that's the proper way. var
toShow
是纯java.lang.Object
的实例,如果我将其转换为FactionProjection
,它的唯一工作方式,我认为这不是正确的方法。 My method:我的方法:
public FactionProjection getFactionById(int id){
Query query = entityManager.createQuery(
"SELECT new com.gamerecords.result_recorder.model.projection.FactionProjection(f.name)" +
"FROM Faction f WHERE f.id = :id",FactionProjection.class)
.setParameter("id",id);
var toShow = query.getSingleResult();
return toShow;
}
constructor:构造函数:
public FactionProjection(String name) {
this.name = name;
}
what I have tried:我尝试过的:
.createQuery
to Faction.class
, or deleting itFaction.class
.createQuery
或将其删除.getSingleResult()
to .getResultList()
.getSingleResult()
更改为.getResultList()
Working code I have now is:我现在的工作代码是:
public FactionProjection getFactionById(int id){
Query query = entityManager.createQuery(
"SELECT new com.gamerecords.result_recorder.model.projection.FactionProjection(f.name)" +
" FROM Faction f WHERE f.id = :id",FactionProjection.class)
.setParameter("id",id);
var toShow = (FactionProjection)query.getSingleResult();
return toShow;
}
I have seen many examples of "select new constructor" expression, and there was no need for casting, which makes me think I'm making a mistake here.我见过很多“选择新构造函数”表达式的例子,并且不需要强制转换,这让我觉得我在这里犯了一个错误。
The normal Query API does not return the exact type of Object you expect and you need to cast.普通查询 API 不会返回您期望的 Object 的确切类型,您需要进行转换。
Query#getSingleResult()
returns an Object
. Query#getSingleResult()
返回Object
。 You can use TypedQuery<T>
instead:您可以改用
TypedQuery<T>
:
TypedQuery<FactionProjection> query;
var result= query.getSingleResult();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.