[英]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.