Reputation: 760
I have entity objects:
@Entity
public class Tag {
@Id
private Long id;
@Transient
private int count;
// getter, setter etc..
}
@Entity
public class Request {
// fileds
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Tag> tag = new HashSet<Tag>();
// getter, setter etc..
}
I need to get all tags with count by Request.
In DAO I make function for it with SQL query:
select tag as id, count(rt.request) as count
from request_tag rt
where rt.request in (...) and rt.request in (...) and etc...
group by rt.tag order by count desc
Tags found but count isn't binding.
How can I bind count from query?
PS:
I don't want to remove @Transient annotation (because I don't want keep count in DB).
I don't want to use @Formula (because it will be slow).
Upvotes: 4
Views: 5242
Reputation: 23624
Option 1:
Create named query with select tag as id, count(rt.request) as count
, after execution you will get Object[2]
cast as expected and use.
Option 2: You can create yet another entity (saying TagStatistic) without @Transient and map it to native(!) named query
@Entity
@Table(name = "Tag")//map to the same table
@NamedNativeQueries({
@NamedNativeQuery(name ="TagStatistic.someName",
resultClass = TagStatistic.class,
query = "select tag as id, count(rt.request) as count ....
...
public class TagStatistic{
...
Upvotes: 1