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

标签 java json spring hibernate rest

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

@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

}

Spring REST Controller :

@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 已在国家/地区表中。问题是当我调用此服务时出现以下错误:

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

任何帮助将不胜感激!

最佳答案

试着把 CascadeType.ALL

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

private Country country;

关于java - 非空属性引用 transient 值 - transient 实例必须在当前操作之前保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19074278/

相关文章:

java - 从 POF 流读取数组

java - 如何将 map 集合与 ICEfaces 数据表组件一起使用

PHP:将传入字符串转换为 UTF-8,没有任何信息它是什么编码

php - 使用 PHP 脚本编辑 JSON 数据

java - 飞行路线集成到现有系统中

java - CLOB : JdbcTemplate : c3p0 - how reuse the same connection?

java - 我的伪 3D 程序正在绘制一个点而不是一条线

Java 优先级解决方法

php - 如何像数组对象一样访问 PHP 中的 JSON 元素?

java - Spring MVC Controller 的运行时加载和动态映射请求/URL