gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:28 24 4
gpt4 key购买 nike

我想从表中选择特定列并将结果存储到非实体 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

最佳答案

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

关于java - @NamedNativeQuery + @SqlResultSetMapping + @ConstructorResult + @ColumnResult 导致 classCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43123238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com