简体   繁体   中英

NamedQuery select returns List<Object>. How to obtain value from Object

I have a select statement that goes into two table and obtain ids from each table. Here is my pseudo code:

Table 1 (study) has study_id

Table 2 (image) has image_id

NamedNativeQuery(name = "test", query = "select study.study_id, image.image_id from study study, image image where image_id=:imageId and study_id=:studyId")

In my code, I have:

Query query = getSession().getNamedNativeQuery("test");
query.setParameter(STUDY_ID, studyId);
query.setParameter(IMAGE_ID, imageId);
List result = query.getResultList(); //result is List<Object>

result is list of Object, where each Object has two values, one study_id and one image_id.

How do I extract these information from Object? What is the best approach to do this?

You can use the @SqlResultSetMapping with @ConstructorResult in the following way:

public class StudyImageIds {

    private final Long studyId;

    private final Long imageId;

    public StudyImageIds(Long studyId, Long imageId) {
        this.studyId = studyId;
        this.imageId = imageId;
    }

    public Long getStudyId() {
        return studyId;
    }

    public Long getImageId() {
        return imageId;
    }
}

// ...

@NamedNativeQuery(
   name = "test",
   query = "select "
         + "  study.study_id as std_id, image.image_id as img_id "
         + "from study study, image image "
         + "where image_id = :imageId and study_id = :studyId",
   resultSetMapping = "study_image_ids_dto"
)
@SqlResultSetMapping(
   name = "study_image_ids_dto",
    classes = @ConstructorResult(
        targetClass = StudyImageIds.class,
        columns = {
            @ColumnResult(name = "std_id"),
            @ColumnResult(name = "img_id")
        }
    )
)

and then use it:

List<StudyImageIds> studyImageIds = session.getNamedQuery("test")
  .setParameter(STUDY_ID, studyId)
  .setParameter(IMAGE_ID, imageId)
  .list();

IMHO this is much more safer and elegant than types casting. See further details in the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM