gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:44:13 25 4
gpt4 key购买 nike

我有实体对象:

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com