简体   繁体   中英

object references an unsaved transient instance - save the transient instance before flushing error

object references an unsaved transient instance - save the transient instance before flushing error

I have 3 entities. I will map each other entity using one to many relationships.

ProductChargeDetail has

@Data
@Entity
public class ProductChargeDetail extends SuperEntity<ProductChargeDetailDto> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long productChargeDetailId;
    @ManyToOne
    @JoinColumn(name = "fuel_type")
    private FuelType fuelType;

    @ManyToOne
    @JoinColumn(name = "cal_type")
    private CalculationType calculationType;


    @Override
    public ProductChargeDetailDto toDto(ModelMapper modelMapper) {
        if (this.fuelType != null)
            productChargeDetailDto.setFuelTypeCode(this.fuelType.getFuelType());
        if (this.calculationType != null)
            productChargeDetailDto.setCalType(this.calculationType.getCalType());
        return productChargeDetailDto;
    }
}

FuelType has

@Data
@Entity
public class FuelType {
    @Id
    @Column(nullable = false, length = 50)
    private String fuelType;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "fuelType", orphanRemoval = true)
    private List<ProductChargeDetail> productChargeDetailList = new ArrayList<>();


}

Calculation type has

@Data
@Entity
public class CalculationType {
    @Id
    @Column(nullable = false)
    private String calType;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "calculationType", orphanRemoval = true)
    private List<ProductChargeDetail> productChargeDetailList;

}

I have a problem when i save the product it throw an error like this. I try using @ManyToOne(cascade = CascadeType.ALL) to the productChargeDetail but when I save a product it shows an error Duplicate error from the application. FuelType and CalculationType have already values in the table. in that case applicatoin save duplicate error when I save this.

Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing: com.misyn.muw.common.entity.ProductChargeDetail.fuelType -> com.misyn.muw.common.entity.FuelType

If the entities you refer to already exist, you should be creating instances to these entities via EntityManager#getReference , which is used by JpaRepository#getOne . This way, you will receive a lazy proxy from Hibernate, for which you don't need to do any cascading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM