javajpanativequery

JPA, @Transient field and Native Query mapping


I have this entity:

@Entity
@Table(name = "entry")
@SqlResultSetMapping(
    name = "viewEntry",
    entities =
    @EntityResult(entityClass = ViewEntry.class,
            fields = {
                    @FieldResult(name="id", column = "id"),
                    @FieldResult(name="guid", column = "guid"),
                    @FieldResult(name="link", column = "link"),
                    @FieldResult(name="descr", column = "descr"),
                    @FieldResult(name="pubDate", column = "pub_date"),
                    @FieldResult(name="read", column = "my_read")
            }
    )
)
public class ViewEntry implements Serializable {
    @Id
    private Integer id;
    private String guid;
    private String link;
    private String descr;
    private Date pubDate;
    @Transient
    private Boolean read;
}

The field read resides in another table, So I made it transient, to prevent JPA mapping errors. To retrieve entity's content I want to use native query that looks like this:

select id,guid,link,descr,pub_date,feed_id,user_id,is_read as my_read from entry join user_to_entry ....
-- skipped dynamic part of query

The problem is that I have no idea how to map native queries to my entity. In particular I don't know if the @Transient field will be ignored by EntityManager. Help, please.


Solution

  • To map results of a native query you can use SqlResultSetMapping http://docs.oracle.com/javaee/7/api/javax/persistence/SqlResultSetMapping.html

    Without a mapping if the columns in the native query matches the attribute name or if they are mapped with @Column in the Entity then you don't need a mapping.