user630209
user630209

Reputation: 1207

On saving the the data with foreign key relations, it throws exception

On saving the the data with foreign key relations, it throws Exception

Sensitivity Entity Class

@Entity
@Table(name="lab_tb_sensitivity")
public class Sensitivity implements Serializable {
    private static final long serialVersionUID = 1L;


    @Id
    @SequenceGenerator(name=EntityConstants.SQ_NAME, sequenceName=EntityConstants.SQ_SS)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator=EntityConstants.SQ__NAME)
    @Column(name="sensitivity_id")
    private long sensitivityId;

    @Column(name="audit_yn")
    private String auditYn;



    //bi-directional many-to-one association to SensitivityPattern
    @OneToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE},fetch = FetchType.LAZY, mappedBy="sensitivity")
    private Set<SensitivityPattern> SensitivityPattern;

    /** Constructor and getters and setters

}

There is a one to many relation ship with SensitivityPattern

SensitivityPattern Entity class

@Entity
@Table(name="lab_tb_sensitivity_pattern")
public class SensitivityPattern implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    private SensitivityPatternPK id;

    private String remarks;

    @ManyToOne
    @JoinColumn(name="sensitivity_id",  nullable = false, insertable = false, updatable = false)
    private Sensitivity sensitivity;

    /**Constructor and geets setters */

}

Primary key is a composite key(sensitivityId + abId) SensitivityPatternPK Entity class ---------------------------------

@Embeddable
public class SensitivityPatternPK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @Column(name="sensitivity_id")
    private long sensitivityId;

    @Column(name="ab_id")
    private long abId;


    /**Constructor and geets setters */

}

On saving code

@Override
public boolean saveSensitivityData(List<SensitivityDto> sensitivity) {

    if(sensitivity != null){

        for(SensitivityDto dto : sensitivity) {
            try {
                updateSensitivityPattern(dto);
                super.saveOneEntity(dto);
            } catch (GenericException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}

/**
 * To update the sensitivity data.
 * @param dto
 */
private void updateSensitivityPattern(SensitivityDto dto) {
    if(dto != null && dto.getSensitivityPattern() != null){
        for(SensitivityPatternDto sPattern : dto.getSensitivityPattern()  ){
            SensitivityPatternPKDto sensitivityPatternPKDto = new  SensitivityPatternPKDto();
            sensitivityPatternPKDto.setSensitivityId(dto.getSensitivityId());
            sPattern.setId(sensitivityPatternPKDto);
            sPattern.setSensitivity(dto);
        }
}

THis is the DAO class to save the data into the database

@Transactional(rollbackOn = GenericException.class)
public D saveOneEntity(D dto) throws GenericException {
    T result;
    try {
        result = repository.save(mapper.map(dto, entityClass));
    } catch (DataAccessException dae) {
        throw new GenericException(dae, dae.getRootCause().getMessage());
    } catch (Exception e) {
        throw new GenericException(
                e,
                messageSource.getMessage(CodeEnum.UNKNOWN_EXCEPTION_ON_SAVE_METHOD.getValue(), null, Locale.ENGLISH));
    }
    return mapper.map(result, dtoClass);
}

On save with the below data on hitting the service with the below data

    {
      "sensitivity": [
        {
          "auditYn": "Y",
          "sensitivityPattern": [
            {
              "id": {
                "abId": 11
              },
              "remarks": "test"
            }
          ]
        }
      ]
    }

It throws the exception

"Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "lab_tb_sensitivity_pattern" violates foreign key constraint "fk_sensitivity_id" Detail: Key (sensitivity_id)=(0) is not present in table "lab_tb_sensitivity".

Upvotes: 0

Views: 369

Answers (1)

ScanQR
ScanQR

Reputation: 3820

Please fix following code,

 try {
       updateSensitivityPattern(dto);
       super.saveOneEntity(dto);
     } 
 catch (GenericException e) {
          e.printStackTrace();
     }

You need to persist first the Sensitivity and then SensitivityPattern. Currently it fails because there is not such entity found hence there is no id generated.

Instead do it,

try {
       //please verify as per you code
       CorrespondingSentivityDTO persistedDTO = super.saveOneEntity(dto);
       updateSensitivityPattern(persistedDTO);
} 
catch (GenericException e) {
          e.printStackTrace();
}

Upvotes: 2

Related Questions