JPA - Setting entity class property from calculated column?

后端 未结 2 1410
有刺的猬
有刺的猬 2021-01-01 03:00

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/gl

相关标签:
2条回答
  • 2021-01-01 03:38

    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;
        ...
    }
    
    0 讨论(0)
  • 2021-01-01 03:42

    AFAIK, JPA doesn't offer standardized support for calculated attributes. With Hibernate, one would use a Formula but EclipseLink doesn't have a direct equivalent. James Sutherland made some suggestions in Re: Virtual columns (@Formula of Hibernate) though:

    There is no direct equivalent (please log an enhancement), but depending on what you want to do, there are ways to accomplish the same thing.

    EclipseLink defines a TransformationMapping which can map a computed value from multiple field values, or access the database.

    You can override the SQL for any CRUD operation for a class using its descriptor's DescriptorQueryManager.

    You could define a VIEW on your database that performs the function and map your Entity to the view instead of the table.

    You can also perform minor translations using Converters or property get/set methods.

    Also have a look at the enhancement request that has a solution using a DescriptorEventListener in the comments.

    All this is non standard JPA of course.

    0 讨论(0)
提交回复
热议问题