非空属性引用瞬态值 \- 瞬态实例必须在当前操作之前保存

新手上路,请多包涵

我有 2 个域模型和一个 Spring REST 控制器,如下所示:

 @Entity
public class Customer{

@Id
private Long id;

@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name="COUNTRY_ID", nullable=false)
private Country country;

// other stuff with getters/setters

}

@Entity
public class Country{

@Id
@Column(name="COUNTRY_ID")
private Integer id;

// other stuff with getters/setters

}

弹簧 REST 控制器:

 @Controller
@RequestMapping("/shop/services/customers")
public class CustomerRESTController {

   /**
    * Create new customer
    */
    @RequestMapping( method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public com.salesmanager.web.entity.customer.Customer createCustomer(@Valid @RequestBody   Customer customer, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        customerService.saveOrUpdate(customer);

        return customer;
    }

    // other stuff
}

我正在尝试使用下面的 JSON 作为正文调用上面的 REST 服务:

 {
    "firstname": "Tapas",
    "lastname": "Jena",
    "city": "Hyderabad",
    "country": "1"
}

国家代码 1 已经存在于 Country 表中。问题是当我调用此服务时出现以下错误:

 org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: com.test.model.Customer.country -> com.test.model.Country; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: com.test.model.Customer.country -> com.test.model.Country

任何帮助将不胜感激!

原文由 Tapas Jena 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 621
2 个回答

尝试放置 CascadeType.ALL

 @OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name="COUNTRY_ID", nullable=false)

private Country country;

原文由 Raju Rudru 发布,翻译遵循 CC BY-SA 3.0 许可协议

我有一个类似的问题。两个实体: DocumentStatusDocumentStatus 有关系 OneToMany ,代表 DocumentStatus 历史。

因此,有一个 @NotNull @ManyToOne Document in Status 的引用。

另外,我需要知道 Document 的实际 状态。所以,我需要另一个关系,这次 @OneToOne ,还有 @NotNull ,在 Document 里面。

问题是:如果两个实体都有 @NotNull 对另一个的引用,我如何才能第一次保留两个实体?

解决方案是:从 @NotNull actualStatus 参考。这样,它就能够保留两个实体。

原文由 djejaquino 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题