java - 如何从 native SQL 查询中绑定(bind)实体对象中的 @Transient 字段

标签 java sql hibernate annotations hql

我有实体对象:

@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

找到标签但计数不具有约束力。

如何从查询中绑定(bind)计数?

附言:

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

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

最佳答案

选项 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{
...

关于java - 如何从 native SQL 查询中绑定(bind)实体对象中的 @Transient 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6424056/

相关文章:

java - 改造:由以下原因引起:java.lang.IllegalArgumentException:无法找到 CustomClass 的调用适配器

java - 如何从 Generic 获取特定的返回类型

java - 将 HashMap 逐个保存到文件

jquery - 按一列无索引或两列其中一列有索引进行搜索

java - 潮人 : Liquibase/Hibernate re-generate initial schema

java - 如何使用 Spring 框架读取和上传 xls 文件?

sql - 如何在oracle中使用其同义词截断任何表?

c# - 如何以编程方式运行 RedShift sql 脚本文件

java - 无法转换为 java.io.Serializable

java - 如何删除@JsonIdentityInfo不必要的Id?