All I need help i create this simple class where Category
have list of Categories
. When i try to save the list of sub categories with the Parent category it's show below error.
Json:-
{
"name": "n11111111",
"detail": "detail",
"status" : "AVAILABLE",
"subCategories": [3, 12, 100, 7, 11] // id of sub-cat
}
Class:-
@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;
}
ERROR:- "message": "could not execute statement; SQL [n/a]; constraint [UK_76grwe00i7mrj7awuvhc3kx0n]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
MYSQL ERROR:- #1062 - Duplicate entry
Code:- Convert from Vo to 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 + " ]");
}
}