0

So I have class like below and trying to implement ManyToOne relationship

        @Entity(name="request_city_id")
        @Table(uniqueConstraints={@UniqueConstraints{columnNames={"request_id","cityId"})})
        @Data
        @NoArgsConstructor
        @FieldDefault(level=AccessLevel.PRIVATE)
        public class RequestCityId{
    
                @GenratedValue(strategy=SEQUENCE, generator="seq_req_city_id")
                @SequenceGenerator(name="seq_req_city_id", allocationSize=1)
                @Column(name="rc_id") 
                @Id
                long id;
                //some other many to one joins
                @ManyToOne
                @JoinColumn(name="request_id")
                Request request;
                String cityId;
                String status;
                RequestCityId(Request req){
                   request= req;}
        }

Existing table:

        @Entity(name="request")
        @Data
        @NoArgsConstructor
        @FieldDefault(level=AccessLevel.PRIVATE)
        public class Request{
            String frequency
            @GenratedValue(strategy=SEQUENCE, generator="seq_req_d")
            @SequenceGenerator(name="seq_req_id", allocationSize=1)
            @Column(name="request_id") 
            @Id
            long id;

            @OneToMany(cascade={ PERSIST, MERGE}, mappedBy="request", fetch=EAGER)
            Set<RequestCityId> requestCityIds;
 
    }

below is serviceClass:

RequestRepository reqRepo; // this class extends crudRespository
public RequestDto merge(RequestDto request){
    Request req= mapper.requestDtoToRequest(request);
    Request enhancedObject = enhanceReq( req);
    Request savedObject = reqRepo.save(enahncedObject);
    return mapper.requestToRequestDto(savedObject)
}

private Request enhanceReq(Request req){
    Set<RequestCityId> requestCityIds= req.getRequestCityIds();
    requestCityIds.foreach(e-> e.setRequest(req));
    return req;
}

but when I am running my code it is trying to insert multiple times, due to that I am getting constraint violation, what should I do to resolve this?

LowCool
  • 1,187
  • 5
  • 25
  • 51

1 Answers1

0

It is because you are attaching plain unmanaged POJO to requestCityIds which then tries to be persisted (inserted) because those are managed entities meaning you dont have to explicit call save to actually update the entity.

In order to avoid this, first persist your object with

Request savedObject = reqRepo.save(enahncedObject);

and then use that savedObject in your method - which now is a managed proxy

private Request enhanceReq(Request saved){
    Set<RequestCityId> requestCityIds= req.getRequestCityIds();
    requestCityIds.foreach(e-> e.setRequest(saved));
    return req;
}

should work then. Obviousyly you have to juggle around with invocation order etc but the main problem of multiple inserts will be gone.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99