Hibernate 自引用表不保存父 ID

Hibernate self reference table not saving parent id

提问人:FARENGElT 提问时间:11/16/2023 最后编辑:FARENGElT 更新时间:11/16/2023 访问量:28

问:

我试图在自我参照表中一次性拯救孩子和他们的父母。但是 db 的子行在保存后父 ID 为空。实体如下所示:

@Entity
@Table(name = "category")
@Data
@EqualsAndHashCode(of = "id")
@ToString(of = "id")
public class Category {

    @Id
    @Column(name = "id", updatable = false, nullable = false)
    @GeneratedValue(generator = Generator.UUID2_GENERATOR_NAME)
    private UUID id;

    @Column(name = "main_category_id")
    private UUID mainCategoryId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "main_category_id", insertable = false, updatable = false)
    private Category mainCategory;

    @OneToMany(mappedBy = "mainCategory", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Category> subCategories;

    @Column(name = "user_id")
    private UUID userId;

    @Column(name = "name")
    private String name;
}

我在两个方向上设置子项和父项,但main_category_id数据库中另存为 null。 保存代码如下所示:

    @Transactional
    public List<CategoryDto> get(UUID userId) {
        List<Category> categoriesToSave = new ArrayList<>();
            for (YoungWithPetCategories cat : YoungWithPetCategories.values()) {
                Category category = new Category();
                category.setName(cat.name());
                category.setUserId(userId);
                List<Category> subCategories = new ArrayList<>();
                for (String subCat : cat.getSubCategories()) {
                    Category subCategory = new Category();
                    subCategory.setName(subCat);
                    subCategory.setMainCategory(category);
                    subCategory.setUserId(userId);
                    subCategories.add(subCategory);
                }
                transactionCategory.setSubCategories(subCategories);
                categoriesToSave.add(transactionCategory);
            }
            categoryRepository.saveAll(categoriesToSave);
    }

我试着拯救孩子,而不是争吵,并立即拯救他们所有人。 有没有可能一次性保存这些自我参照实体,或者我应该将它们分开保存?

Java Hibernate 一对多 引用自 引用表

评论

0赞 FARENGElT 11/21/2023
解决了删除“insertable = false, updatable = false”和“private UUID mainCategoryId;”

答: 暂无答案