I have a large database row, and want to only fetch some specific colums. Ideally they should be automatically mapped to my @Entity
.
I tried the following, which did not work, as somehow the id attribute is required. Why?
@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
}
Execution:
getEntityManager().createNamedQuery("testQuery", MyEntity.class);
Result:
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.
Even if I write SELECT id, city FROM mytable
I would get: The column country was not found in the ResultSet.` So somehow every column that is present in the database, but not selected by the query, causes this failure. Why?
Regarding the duplicate mark:
Quote from that anser:
@NamedNativeQuery(
name="jedisQry",
query = "SELECT name,age FROM jedis_table",
resultClass = Jedi.class
)
Then, we can simply do:
TypedQuery<Jedi> query = em.createNamedQuery("jedisQry", Jedi.class);
List<Jedi> items = query.getResultList();
Well, if that's the solution, it is exactly the same as my question code. Any for me it does not work??
Solution in my case:
@NamedNativeQuery(
name = "testQuery",
query = "SELECT city FROM mytable",
resultSetMapping = "testResultSet"
)
@SqlResultSetMapping(
name = "testResultSet",
classes = {
@ConstructorResult(
targetClass = MyEntity.class,
columns = {
@ColumnResult(name = "city")
}
)
}
)