gpt4 book ai didi

java - thymeleaf 中对 @OneToMeny 和 @ManyToOne 类的无尽 hibernate 查询

转载 作者:行者123 更新时间:2023-12-01 16:22:37 25 4
gpt4 key购买 nike

各位,我自己创建了两个正在流通的类(class)。

添加剂类

@Entity
@Table(name = "additive", schema = "dbo")
@Data
@NoArgsConstructor
public class Additive{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "additive_id")
private Integer id;

@ManyToOne(targetEntity = AdditiveType.class, fetch = FetchType.LAZY)
@JoinColumn(name = "additive_type_id")
private AdditiveType additiveType;

private String description;
private BigDecimal price;
}

以及带有类型的类

@Entity
@Table(name = "additive_type", schema = "dbo")
@Data
@NoArgsConstructor
public class AdditiveType{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "additive_type_id")
private Integer id;

@OneToMany(targetEntity = Additive.class, fetch = FetchType.LAZY)
@JoinColumn(name = "additive_type_id")
private Set<Additive> additives;

private String description;
}

当我尝试使用 thymeleaf 显示代码时

<div th:each="aType:${types}">
<h2 th:text="${aType.description}">type</h2>
<div>
<div th:each="additive:${aType.additives}">
<div>
<img alt="${additive.description}"
src="...">
<div>
<h5 th:text="${additive.description}">additive description</h5>
</div>
<div>
<form method="post"
th:action="...">
<input name="id" th:value="${additive.id}" type="hidden"/>
<button type="submit">select this</button>
</form>
</div>
</div>
</div>
</div>
</div>

即使提取类型被标记为惰性fetch = FetchType,我也会从一个表additive一次从另一个additive_type对数据库进行无休止的查询。懒惰

如何解决这个问题?

更新

不幸的是,@JsonIgnoreProperties@JsonIgnore 都没有导致循环查询中断。我在其余服务中使用了这些注释并且它在那里工作。在 thymeleaf 这里,它没有带来预期的效果。

最佳答案

我认为您遇到了循环序列化问题。

您有一个AdditiveAdditiveTypesAdditives 相关有AdditiveTypesAdditives 相关....等等,等等。

解决该问题的一种方法是用 @JsonIgnoreProperties 注释您的类属性之一。例如:

@Entity
@Table(name = "additive_type", schema = "dbo")
@Data
@NoArgsConstructor
public class AdditiveType{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "additive_type_id")
private Integer id;

@OneToMany(targetEntity = Additive.class, fetch = FetchType.LAZY)
@JoinColumn(name = "additive_type_id")
@JsonIgnoreProperties("additiveType")
private Set<Additive> additives;

private String description;
}

所以当序列化 AdditiveType 时,内部的additiveTypes不会被序列化。

更新

而且我认为如果你只用 @JsonIgnore 进行注释然后Additives AdditiveTypes的根本不会被序列化

关于java - thymeleaf 中对 @OneToMeny 和 @ManyToOne 类的无尽 hibernate 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62232047/

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