Home > database >  Entity Manager Not Returning Column Names
Entity Manager Not Returning Column Names

Time:07-04

i'm querying a table through entity manager, it returns a resultList but it only returns the values and not the column names (ss attached) which is obvious because I am not providing the Entity class to map the result to. i can not provide the exact entity class as the scenario i'm dealing with is dynamic and i do not know what entity will be returned in the resultSet which is why i have only provided a parent class which is not a mapped entity. however i do know that the entity will contain a specific columns and they are known. is there a way i can map this resultSet to a class on modify it to return the column names as well?

Query emQuery = entityManager.createNativeQuery(query.toString());
        List<MasterDataSource> objectList = emQuery.getResultList();

here are the contents of the list returned which shows that it's not returning the name rather values only.

enter image description here

Parent class is below

enter image description here

CodePudding user response:

figured it out, use @SqlResultSetMapping and provide the column names and types.

@SqlResultSetMapping(name="datasourceResult", classes = {
        @ConstructorResult(targetClass = MasterDataSource.class,
                columns = {@ColumnResult(name="id", type = Long.class), @ColumnResult(name="data", type = String.class),
                        @ColumnResult(name="account_id", type = String.class),@ColumnResult(name="data_type", type = String.class),
                        @ColumnResult(name="create_datetime", type = String.class),@ColumnResult(name="data_interface", type = String.class),
                        @ColumnResult(name="record_seq_no", type = Integer.class),@ColumnResult(name="source_file_name", type = String.class),
                        @ColumnResult(name="source_file_path", type = String.class),@ColumnResult(name="destination", type = String.class),
                        @ColumnResult(name="is_processed", type = Boolean.class)})
})

this requires a constructor for all above fields since I am using @ConstructorResult

usage: use the name of the of the @SqlResultSetMapping in your createNativeQuery call

Query emQuery = entityManager.createNativeQuery(query.toString(), "datasourceResult");
@SuppressWarnings("unchecked")
List<yourType> objectList = emQuery.getResultList();
  • Related