Search code examples
javaspring-bootspring-dataunique-constraintspring-repositories

Search by two unique fields spring boot for uniqueness


I created a child entity:

public class ChildEntity  {
   private Long bookNo;
   private String bookType;
}

Those two fields are together unique. Some kind of data:

| No | Type      |
|----|-----------|
| 1  | Classical |
| 2  | Classical |
| 2  | Scifi     |
| 3  | Scifi     |
| 1  | Classical | (Error for uniqueness

I created this entity to search inside the parent entity.

public class ParentEntity{
    @ManyToOne
    private ChildEntity child;    
    //and other fields here
}

Also, there are 2 different parent entities. They have to be different entity, they have a few different fields. But this child entity is common. So, I will use those child entities to compare / take difference between data tables because only unique areas are in that child entity ones. I can take difference of data tables via that child entity fields.

I made ManyToOne because many different parents can have the same child.

I create parent entities in a service like this:

private createParentEntity(Dto dto){
    
    ParentEntity parent = new ParentEntity();
    //set other fields from dto
    parent.setAge(dto.getAge);
    
    ChildEntity child = new ChildEntity();
    child.setBookNo(dto.getBookNo());
    child.setBookType(dto.getBookType());
    
    parent.setChild(child);//here is problem , please look down
}

What my problem is, the line I put a comment.

Same child entities can come, so when I save parents, it will try to save the child again and can get a unique constrain error? What can I do to do this?

Because in the end, I will use spring data to search like this inside parent repository:

parentEntityRepository.findByChild(ChildEntity child);
@UniqueConstraints = {
    @UniqueConstraint(
         name = "uq_general_checklist_ordinal",
         columnNames = {"book_no", "book_type"}
    )
}
public class ChildEntity {
   @Id
   private Long bookNo;
    
   @Id
   private String bookType;
}

Is that a good solution to put both Ids? Or here, I should first save the child and check if it exists or not?

ChildEntity child =childRepository.findByBookNoAndBookType(
     dto.getBookNo(), 
     dto.getBookType()
);//if exists, set to parent. if not, create new and set it?

Solution

  • I'd do something like this: "Or here, i should first save child and check if exists or not?"

    However, instead of saving the child first, just search for a child with the new IDs. This way, you avoid SQL Exceptions. If it doesn't exist, still dont save the child. Add it to the parent and save the parent. It will consequently save the child. If it exists, add it to the new parent and save the parent.