I have problem with Spring Data JPA. I want to create a category that have parent category with the same table. Some categories don't need to have parent category, so parent category can be null. but when I do that, and save it, it shown error as below:
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
Here is my model:
@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;
}
- When saving object, I use save method of CRUDRepsoitory.
Here is my view:
<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>