大家
我为自己建立了两个正在循环的课程。

加法类

@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;
}



当我尝试使用百里香显示代码时

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


我从一个表additive一次从另一个additive_type到数据库一次无休止的查询,即使将获取类型标记为惰性fetch = FetchType.LAZY

您如何补救?

更新

不幸的是,@JsonIgnoreProperties@JsonIgnore都没有导致通函查询中断。我在rest服务中使用了这些批注,并且在那里工作了。在百里香,这并没有达到预期的效果。

最佳答案

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

您有一个Additive,它的AdditiveTypesAdditives有关,而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进行注释,则AdditivesAdditiveTypes根本不会序列化

10-06 07:27