首页 > 解决方案 > @OneToMany 与它的自我类

问题描述

我需要的只是帮助我创建了这个简单的类,其中Category包含Categories. 当我尝试使用父类别保存子类别列表时,它显示在错误下方。

杰森:-

{
    "name": "n11111111",
    "detail": "detail",
    "status" : "AVAILABLE",
    "subCategories": [3, 12, 100, 7, 11] // id of sub-cat
}

班级:-

@Entity
@Table(name = "category")
public class Category{

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(nullable = false, updatable = false, name = "category_id")
    private Long id;

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

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

    @Column(nullable = false, name = "status")
    @Enumerated(EnumType.ORDINAL)
    private Status status;

    @OneToMany( targetEntity=Category.class, cascade=CascadeType.ALL)
    private List<Category> subCategories;

}

错误:-"message": "could not execute statement; SQL [n/a]; constraint [UK_76grwe00i7mrj7awuvhc3kx0n]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",

MYSQL 错误:-#1062 - Duplicate entry

代码:- 从 Vo 转换为 POJO

private Categorie getCatToPojo(CategorieVo categorieVo, String type) {
    double startTime = System.nanoTime();
    logger.info("Start Vo To Pojo Categorie");
    // #:- case:-1 when no sub-cat there it save only below 3 attribute
    this.categorie = new Categorie();
    this.saveNameCat(categorieVo, type);
    this.categorie.setDetail(categorieVo.getDetail());
    this.categorie.setStatus(categorieVo.getStatus());
    // #:- case:-2 when have list of sub-cat then will exe then next process
    if((CollectionUtils.isNotEmpty(categorieVo.getSubCategories()) && categorieVo.getSubCategories().size() > 0) && type.equalsIgnoreCase("P")) {
        logger.debug("Sub-Process....SubCategories...init");
        // #:- S-Cat will be get and
        List<Categorie> subCategories = this.businessServer.findAllById(categorieVo.getSubCategories())
                .stream().filter(categorie1 -> categorie1.getName().startsWith("S-") == true ).collect(Collectors.toList());
        // #:- if any wrong id pass it will not give you the list
        if(CollectionUtils.isNotEmpty(subCategories) && subCategories.size() > 0) {
            this.categorie.setSubCategories(subCategories);
        }
        logger.debug("Sub-Process....SubCategories...End " + categorieVo.getSubCategories().toString());
    }
    logger.debug(SecurityUtil.getPerfLog("Process Time For Convert the Vo to POJO", this.categorie.toString(), startTime));
    logger.info("End Vo To Pojo Categorie");
    return categorie;
}

private void saveNameCat(CategorieVo categorieVo, String type) {

    switch (type) {
        case "P":
            // #:- P,S will join with name
            this.categorie.setName(type + "-" + categorieVo.getName());
            break;
        case "S":
            // #:- P,S will join with name
            this.categorie.setName(type + "-" + categorieVo.getName());
            break;
        default:
            logger.info("End Vo To Pojo Categorie With Exception");
            // #:- will throw error bad request of type
            throw new BadTypeException(" [ " + "Bad Request Type" + " ]--[ " + type + " ]");
    }
}

标签: javahibernatespring-mvcjpaspring-data-jpa

解决方案


一旦我必须做完全相同的事情。这是用于相同目的的工作代码:

@Entity
@Data
@NoArgsConstructor
@Table(name = "categories")
public class Category {
    @JsonProperty("Id")
    @Id
    private int id;

    @JsonProperty("Code")
    private String code;

    @JsonProperty("Name")
    private String name;

    @JsonProperty("ParentId")
    @Column(name = "parent_id")
    private Integer parent;

    @JsonProperty("NewAdminId")
    private int newAdminId;

    @JsonProperty("VolumetricWeight")
    @Column(name = "volumetricWeight")
    private Float volumetricWeight = 0.0f;

    @JsonProperty("Nodes")
    @OneToMany(
            cascade = CascadeType.ALL,
            fetch = FetchType.EAGER,
            orphanRemoval = true)
    @JoinColumn(name = "parent_id")
    private List<Category> categories;

    public Category(int id, String code, String name, int newAdminId, List<Category> categories) {
        this.id = id;
        this.code = code;
        this.name = name;
        this.newAdminId = newAdminId;
        this.categories = categories;
    }
}

推荐阅读