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

Tap*_*ena 35 java rest spring json hibernate

我有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

}
Run Code Online (Sandbox Code Playgroud)

Spring 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
}
Run Code Online (Sandbox Code Playgroud)

我试图用以下JSON作为主体调用上面的REST服务:

{
    "firstname": "Tapas",
    "lastname": "Jena",
    "city": "Hyderabad",
    "country": "1"
}
Run Code Online (Sandbox Code Playgroud)

国家代码1已存在于国家/地区表中的位置.问题是当我调用此服务时出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Raj*_*dru 40

尝试使用CascadeType.ALL

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

private Country country;
Run Code Online (Sandbox Code Playgroud)

  • 好的,然后做一件事.您的客户对象具有ID为1的国家/地区对象.但该国家/地区对象未处于持久状态.首先通过发送国家ID获取国家/地区对象 将从数据库检索的国家/地区对象设置为Customer对象.然后保存客户对象.我希望这次它不会给出任何错误. (8认同)

dje*_*ino 14

我遇到了类似的问题.两个实体:文档状态. 文件过关系OneToMany地位,那代表的历史地位文件了.

因此,有一个文件内部状态@NotNull @ManyToOne参考.

另外,我需要知道实际情况文件.所以,我需要另一种关系,这次@OneToOne也是@NotNullDocument中.

问题是:如果两个实体都@NotNull引用另一个实体,我怎么能第一次坚持这两个实体呢?

解决方案是:@NotNullactualStatus参考中删除参考.这样,它就能够持久化两个实体.

  • 我提出了一个类似于我的问题的解决方案.与新问题无关. (15认同)