【问题标题】:How can binding @Transient field in entity object from native SQL query如何从本机 SQL 查询中绑定实体对象中的 @Transient 字段
【发布时间】:2011-06-21 10:49:05
【问题描述】:

我有实体对象:

@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..
}

我需要通过请求获取所有带有计数的标签。

在 DAO 中,我使用 SQL 查询为它创建函数:

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

已找到标签,但计数未绑定。

如何从查询中绑定计数?

PS:

  1. 我不想删除 @Transient 注释(因为我不想在 DB 中保留计数)。

  2. 我不想使用@Formula(因为它会很慢)。

【问题讨论】:

    标签: java sql hibernate annotations hql


    【解决方案1】:

    选项 1: 使用select tag as id, count(rt.request) as count 创建命名查询,执行后您将按预期获得Object[2] 并使用。

    选项 2: 您可以在没有 @Transient 的情况下创建另一个实体(例如 TagStatistic) 并将其映射到本地(!)命名查询

    @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{
    ...
    

    【讨论】:

    • 一切都容易多了...只需使用@SqlResultSetMapping。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2013-10-09
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多