Reputation: 5947
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.
Upvotes: 0
Views: 17006
Reputation: 41
In the worst case, you can create a view with your join and map your view like a normal table. You just need to delete that new table that hibernate will create for you.
https://www.w3schools.com/sql/sql_view.asp
Upvotes: 0
Reputation: 24423
You can map the field in another table by using @SecondaryTable
in your entity. Something like this:
...
@SecondaryTable(name="user_to_entry",
pkJoinColumns=@PrimaryKeyJoinColumn(name="entry_id"))
public class ViewEntry implements Serializable {
@Id
private Integer id;
private String guid;
private String link;
private String descr;
@Column(name="pub_date")
private Date pubDate;
@Column(table = "user_to_entry")
private Boolean read;
}
If you can't do that for some reason, you can map the native SQL results to entity like this
em.createNativeQuery("<native SQL>", ViewEntry.class)
but I don't think this will map a transient field (I could be wrong, haven't tested it).
Third option is to use @SqlResultSetMapping
, but I'm also not sure this will work with transient fields. Check this for an example.
Upvotes: 3
Reputation: 36143
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.
Upvotes: 2