当前位置: 首页 > 知识库问答 >
问题:

对象引用一个未保存的瞬态实例-在所涉及的hibernate主表中刷新之前保存瞬态实例

严阳秋
2023-03-14

我有一个名为bmu_mstr的主表,对应的实体类是

@Entity
@Table(name = "bmu_mstr")
@JsonIgnoreType
//@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property="@bmuId")
public class BmuMaster implements Serializable{


    private static final long serialVersionUID = -8284996311089344328L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "bmu_id", unique = true, nullable = false)
    private Integer bmuId;

    @Column(name = "bmu_desc")
    private String bmuDesc;

    public BmuMaster() {
    }

    public BmuMaster(Integer bmuId) {
        this.bmuId = bmuId;
@Entity
@Table(name = "comp_rsc_move_employee")
public class CompRscEmployee implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer rscId;

    @ManyToOne
    @JoinColumn(name = "transfer_from")
    private BmuMaster transferFrom;

    @ManyToOne
    @JoinColumn(name = "transfer_to")
    private BmuMaster transferTo;
        CompRscEmployee compRscEmployee = new CompRscEmployee();


        compRscEmployee.setTransferFrom(new BmuMaster(employeeDetails.getTransferFrom()));
        compRscEmployee.setTransferTo(new BmuMaster(employeeDetails.getTransferTo()));

        CompRscEmployee rscEmp = compDao.saveOrUpdate(compRscEmployee)
                .orElseThrow(() -> new CommonException("Unable to save or update CompRscEmployee data"));

共有1个答案

郭建华
2023-03-14

您应该从数据库中加载BMUMaster实例,而不是创建新实例,以便传递到SetTransferFromSetTransferTo方法中。

不确定您的代码是如何设置的,但类似于以下内容


BmuMaster from = masterDao.findById(employeeDetails.getTransferFrom())
        .orElseThrow(() -> new CommonException("Unable to find department" + employeeDetails.getTransferFrom()));
BmuMaster to = masterDao.findById(employeeDetails.getTransferTo())
        .orElseThrow(() -> new CommonException("Unable to find department" + employeeDetails.getTransferTo()));

CompRscEmployee compRscEmployee = new CompRscEmployee();
compRscEmployee.setTransferFrom(from);
compRscEmployee.setTransferTo(to);

CompRscEmployee rscEmp = compDao.saveOrUpdate(compRscEmployee)
        .orElseThrow(() -> new CommonException("Unable to save or update CompRscEmployee data"));
 类似资料: