[英]How to initialize fields with size others fields in entity JPA
我有一个示例 JPA 实体:
@Entity
@Table(name = "tb_group")
public class Group
{
...
@ManyToMany
@JoinTable(name = "tb_group_user",
joinColumns = @JoinColumn(name = "fk_group_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "fk_user_id", referencedColumnName = "id"))
private List<User> users;
private Integer userSize;
...
}
我的问题是,如何使用用户字段的大小值初始化 userSize 字段,即延迟加载字段?
我知道这是一个愚蠢的问题,但我找不到解决这个问题的好策略。
我尝试了这个解决方案,但没有成功:
private Integer userSize = users.size();
我对这个问题感到困惑。 你能帮我举个例子吗?
编辑:
我尝试了Ady Junior建议的解决方案@Formula("select count(gu.fk_user_id) from tb_group_user gu where gu.fk_group_id = id")
,但是当我尝试获取组时,我收到了这个例外:
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax to use near
select count(gu.fk_user_id) from tb_group_user gu where gu.fk_group_id = group
ERROR br.com.loopec.loopkey.server.controller.ExceptionsHandler
Unhandled Exception: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
编辑2:
我得到它解决了这个问题。 Ady Junior给了我一个很好的解决方案,错误是由于我的愚蠢。 在@Formule("select count(gu.fk_user_id) from tb_group_user gu where gu.fk_group_id = id")
里面我忘记了查询之间的括号'('')'。
我的问题的正确解决方案是:
@Entity
@Table(name = "tb_group")
public class Group
{
...
@ManyToMany
@JoinTable(name = "tb_group_user",
joinColumns = @JoinColumn(name = "fk_group_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "fk_user_id", referencedColumnName = "id"))
private List<User> users;
@Formula("(select count(gu.fk_user_id) from tb_group_user gu where gu.fk_group_id = id)")
private Integer userSize;
...
}
您可以将超懒 collections 与@LazyCollection(LazyCollectionOption.EXTRA)
一起使用,但我不建议这样做: https://vladmihalcea.com/hibernate-extra-lazy-collections/
Ady Junior 提出的方法即使用@Formula("select count(gu.fk_user_id) from tb_group_user gu where gu.fk_group_id = id")
是一种你可以使用 go 的方法,但可能最好使用 DTO 查询并确定大小在用于加载数据的查询中。 像这样的东西
entityManager.createQuery("SELECT g.name, SIZE(g.users) FROM Group g")
devsaleh,尝试使用@Formula 编写计数查询。
这个注解有很多特点。 例如,在 Vlad Mihalcea 写的这篇很棒的帖子中: https://vladmihalcea.com/how-to-map-calculated-properties-with-jpa-and-hibernate-formula-annotation/
@Entity
@Table(name = "tb_group")
public class Group
{
...
@ManyToMany
@JoinTable(name = "tb_group_user",
joinColumns = @JoinColumn(name = "fk_group_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "fk_user_id", referencedColumnName = "id"))
private List<User> users;
@Formula("(select count(gu.fk_user_id) from tb_group_user gu where gu.fk_group_id = id)")
private Integer userSize;
...
}
@devsaleh,非常感谢!
此致!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.