"select new constructor" 查询 returns java.lang.Object 而不是构造函数的实例 class
"select new constructor" query returns java.lang.Object instead of instance of constructors class
var toShow
是纯 java.lang.Object
的实例,如果我将它转换为 FactionProjection
,它的唯一工作方式我不认为这是正确的方式。我的方法:
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;
}
构造函数:
public FactionProjection(String name) {
this.name = name;
}
我尝试过的:
- 将
.createQuery
的第二个参数更改为 Faction.class
,或者
删除它
- 将方法
.getSingleResult()
更改为 .getResultList()
我现在的工作代码是:
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;
}
我看过很多“select new constructor”表达式的例子,而且不需要转换,这让我觉得我在这里犯了一个错误。
普通查询 API 不 return 您期望的对象的确切类型,您需要转换。 Query#getSingleResult()
return 一个 Object
。您可以使用 TypedQuery<T>
代替:
TypedQuery<FactionProjection> query;
var result= query.getSingleResult();
var toShow
是纯 java.lang.Object
的实例,如果我将它转换为 FactionProjection
,它的唯一工作方式我不认为这是正确的方式。我的方法:
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;
}
构造函数:
public FactionProjection(String name) {
this.name = name;
}
我尝试过的:
- 将
.createQuery
的第二个参数更改为Faction.class
,或者 删除它 - 将方法
.getSingleResult()
更改为.getResultList()
我现在的工作代码是:
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;
}
我看过很多“select new constructor”表达式的例子,而且不需要转换,这让我觉得我在这里犯了一个错误。
普通查询 API 不 return 您期望的对象的确切类型,您需要转换。 Query#getSingleResult()
return 一个 Object
。您可以使用 TypedQuery<T>
代替:
TypedQuery<FactionProjection> query;
var result= query.getSingleResult();