关于以下示例,是否可以检索 AnsweredQuestion 实例列表作为 Question 的对象?
@MappedSuperclass
public abstract class Question{
@Column(name="TITLE")
private String title;
...
}
@Entity
@Table(name="ANSWEREDQUESTION")
public class AnsweredQuestion extends Question
{
@Column(name="ANSWER")
private String answer;
...
}
对我来说,只检索几列非常重要,因为后代类有很多列。 我尝试了如下操作,但它仍然返回 AnsweredQuestion 列表:
queryStr = " select q from AnsweredQuestion q where ..."
TypedQuery<Question> query = entityManager.createQuery(queryStr, Question.class);
return query.setParameter( ... ).getResultList();
最佳答案
如果需要返回几个字段,也可以选择它们并使用new
运算符:
TypedQuery<Sample> query = entityManager.createQuery("select new com.acme.sample.Sample(e.fieldA, e.fieldB) from AnsweredQuestion e", Sample.class);
return query.setParameter( ... ).getResultList();
JPA 实现将查找 Sample
构造函数(路径必须完整)并在转换结果时调用它。避免返回数据库必须返回的所有内容非常方便(以创建新类来表示结果为代价):)
关于java - JPA - 是否可以将结果作为 @MappedSuperclass 的实例获得?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206261/