JPA - 从计算列设置实体类属性? [英] JPA - Setting entity class property from calculated column?
问题描述
我正在使用在Glassfish 3上运行的简单Java Web应用程序来处理JPA(持久性提供程序是EclipseLink)。到目前为止,我真的很喜欢它(netbeans / glassfish交互中的错误除外)但是我希望能够做到这一点,我不知道该怎么做。
I'm just getting to grips with JPA in a simple Java web app running on Glassfish 3 (Persistence provider is EclipseLink). So far, I'm really liking it (bugs in netbeans/glassfish interaction aside) but there's a thing that I want to be able to do that I'm not sure how to do.
我有一个映射到数据库表(article)的实体类(Article)。我正在尝试对返回计算列的数据库进行查询,但我无法弄清楚如何设置Article类的属性,以便在调用查询时属性由列值填充。
I've got an entity class (Article) that's mapped to a database table (article). I'm trying to do a query on the database that returns a calculated column, but I can't figure out how to set up a property of the Article class so that the property gets filled by the column value when I call the query.
如果我定期选择id,title,body from article查询,我会得到一个精美的Article对象列表,其中填充了id,title和body属性。这很好。
If I do a regular "select id,title,body from article" query, I get a list of Article objects fine, with the id, title and body properties filled. This works fine.
但是,如果我这样做:
Query q = em.createNativeQuery("select id,title,shorttitle,datestamp,body,true as published, ts_headline(body,q,'ShortWord=0') as headline, type from articles,to_tsquery('english',?) as q where idxfti @@ q order by ts_rank(idxfti,q) desc",Article.class);
(这是在Postgres上使用tsearch2进行全文搜索 - 这是一个特定于数据库的函数,所以我' m使用NativeQuery)
(this is a fulltext search using tsearch2 on Postgres - it's a db-specific function, so I'm using a NativeQuery)
你可以看到我正在获取一个名为headline的计算列。如何在我的文章类中添加标题属性,以便它被此查询填充?
You can see I'm fetching a calculated column, called headline. How do I add a headline property to my Article class so that it gets populated by this query?
到目前为止,我已经尝试将其设置为@Transient,但是最终只是因为它一直是空的。
So far, I've tried setting it to be @Transient, but that just ends up with it being null all the time.
推荐答案
可能没有好办法,只能手动:
There are probably no good ways to do it, only manually:
Object[] r = (Object[]) em.createNativeQuery(
"select id,title,shorttitle,datestamp,body,true as published, ts_headline(body,q,'ShortWord=0') as headline, type from articles,to_tsquery('english',?) as q where idxfti @@ q order by ts_rank(idxfti,q) desc","ArticleWithHeadline")
.setParameter(...).getSingleResult();
Article a = (Article) r[0];
a.setHeadline((String) r[1]);
-
@Entity
@SqlResultSetMapping(
name = "ArticleWithHeadline",
entities = @EntityResult(entityClass = Article.class),
columns = @ColumnResult(name = "HEADLINE"))
public class Article {
@Transient
private String headline;
...
}
这篇关于JPA - 从计算列设置实体类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!