@NamedNativeQuery + @SqlResultSetMapping + @ConstructorResult + @ColumnResult导致classCastException

时间:2017-03-30 16:17:18

标签: java spring hibernate jpa

我想从表中选择特定列并将结果存储到非实体POJO。

我的实体课程:

@Entity
@Table(name = "CUSTOMER")
@NamedNativeQuery(name = "findSampleMapping", 
    query = "SELECT CUSTOMER_ID, NAME, REG_TIMESTAMP FROM CUSTOMER where CUSTOMER_ID = ?1", resultSetMapping = "SampleMapping")
@SqlResultSetMapping(name="SampleMapping",
classes = {
 @ConstructorResult(targetClass = com.entity.Sample.class,
   columns = {@ColumnResult(name="customerId"), @ColumnResult(name="name"), @ColumnResult(name="regTimeStamp")}
 )}
)
public class CustomerEntity {

    @Id
    @Column(name = "CUSTOMER_ID")
    private String customerId;

    @Column(name = "NAME")
    private String name;

    @Column(name = "FIRST_NAME")
    private String firstName;

   @Column(name = "LAST_NAME")
    private String lastName;

   @Column(name = "REG_TIMESTAMP ")
    private String regTimeStamp;
}

非实体POJO:

import java.sql.Timestamp;

    public class Sample {

        private String customerId;
        private String name;
        private TimeStamp regTimeStamp;

        public Sample(String customerId, String name, TimeStamp regTimeStamp){
            this.customerId = customerId;
            this.name = name;
            this.regTimeStamp= regTimeStamp;
        }

        public String getCustomerId() {
            return customerId;
        }
        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getRegTimeStamp() {
            return regTimeStamp;
        }
        public void setRegTimeStamp(String regTimeStamp) {
            this.regTimeStamp= regTimeStamp;
        }

    }

致电:

Query q = em.createNamedQuery("findSampleMapping");
q.setParameter(1, "1");
@SuppressWarnings("unchecked")
List<Sample> list = q.getResultList();

   for (Sample row : list) {
    System.out.println(row.getCustomerId());
   }

当我尝试循环并获取值时,我在for循环Ljava.lang.Object中得到classCastException;无法转换为com.entity.Sample

1 个答案:

答案 0 :(得分:0)

List<Sample> list = q.setResultTransformer(Transformers.aliasToBean(Sample.class)).getResultList();