我有一个大型数据库行,并且只想获取一些特定的列。理想情况下,它们应自动映射到我的@Entity
。
我尝试了以下操作,但这不起作用,因为某种方式需要id属性。为什么呢?
@Entity
@NamedNativeQuery(
name = "testQuery",
query = "SELECT city FROM mytable",
resultClass = MyEntity.class
)
public class MyEntity {
@Id
private int id;
private String country;
private String city;
public MyEntity() {
}
//getter+setter for all attributes
}
执行:
getEntityManager().createNamedQuery("testQuery", MyEntity.class);
结果:
WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper: SQL Error: 0, SQLState: 42703
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper: The column id was not found in the ResultSet.
ERROR : PSQLException: The column id was not found in the ResultSet.
即使我写SELECT id, city FROM mytable
,我也会得到:在ResultSet中找不到列国家。因此,数据库中存在但查询未选中的每一列都会导致此失败。为什么呢?
关于重复标记:
引用那个anser:
@NamedNativeQuery(
name="jedisQry",
query = "SELECT name,age FROM jedis_table",
resultClass = Jedi.class
)
然后,我们可以简单地做:
TypedQuery<Jedi> query = em.createNamedQuery("jedisQry", Jedi.class);
List<Jedi> items = query.getResultList();
好吧,如果这是解决方案,它与我的问题代码完全相同。对我来说它不起作用??
我的解决方案:
@NamedNativeQuery(
name = "testQuery",
query = "SELECT city FROM mytable",
resultSetMapping = "testResultSet"
)
@SqlResultSetMapping(
name = "testResultSet",
classes = {
@ConstructorResult(
targetClass = MyEntity.class,
columns = {
@ColumnResult(name = "city")
}
)
}
)