具有可空外键的Spring Data JPA自连接

时间:2018-07-16 13:26:00

标签: spring-boot spring-data-jpa spring-data thymeleaf

我对Spring Data JPA有问题。我想创建一个具有相同表的父类别的类别。有些类别不需要父类别,因此父类别可以为null。但是,当我这样做并保存时,它显示如下错误:

org.hibernate.TransientPropertyValueException: object references an unsaved 
transient instance - save the transient instance before flushing : 
com.ltech.solutions.ecom.models.category.Category.parent -> 
com.ltech.solutions.ecom.models.category.Category

这是我的模特:

@Entity
@Table(name = "tb_category")
public class Category extends BaseEntity {

    @Column(name = "name", nullable = false)
    private String name;

    @JsonIgnore
    @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    private Category parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    @JsonProperty(value = "sub_categories")
    private Set<Category> subCategories;

    @Column(name = "is_visible", insertable = false, columnDefinition = 
    "BOOLEAN DEFAULT TRUE")
    @JsonProperty(value = "is_visible")
    private Boolean isVisible;

    @Column(name = "is_enable", insertable = false, columnDefinition = "BOOLEAN 
    DEFAULT TRUE")
    @JsonProperty(value = "is_enable")
    private Boolean isEnable;

    @Column(name = "desc_attribute")
    private String descAttribute;
 }
  • 保存对象时,我使用CRUDRepsoitory的保存方法。

这是我的观点:

<form th:object="${createCategoryForm}" th:action="@{/category/save}" 
method="post">
        <fieldset>
            <legend>Create Category</legend>
            <div class="form-group">
                <label>Name</label>
                <input class="form-control" th:field="*{name}" />
            </div>
            <div class="form-group">
                <label>Code</label>
                <input class="form-control" th:field="*{code}" />
            </div>
            <div class="form-group">
                <label>Description (English)</label>
                <input class="form-control" th:field="*{descEn}" />
            </div>
            <div class="form-group">
                <label>Description (Khmer)</label>
                <input class="form-control" th:field="*{descKh}" />
            </div>
            <div class="form-group">
                <label>Attribute</label>cs
                <input class="form-control" th:field="*{descAttribute}" />
            </div>
            <div class="form-group">
                <label>Parent of</label>
                <select class="form-control" th:field="*{parent.id}">
                    <option value="">None</option>
                    <option th:each="parent : ${parentCategories}" th:value="${parent.id}" th:text="${parent.name}"></option>
                </select>
            </div>
            <input type="submit" />
        </fieldset>
    </form>

0 个答案:

没有答案