Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not-null property references a transient value - transient instance must be saved before current operation

I have 2 domain models and one Spring REST Controller like below:

@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
}

I am trying to call above REST service with below JSON as body:

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

Where country code 1 is already there in Country table. The problem is when I am calling this service getting below error:

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

Any help will be appreciated!

like image 998
Tapas Jena Avatar asked Sep 29 '13 04:09

Tapas Jena


2 Answers

Try putting CascadeType.ALL

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

private Country country;
like image 175
Raju Rudru Avatar answered Nov 16 '22 08:11

Raju Rudru


I had a similar problem. Two entities: Document and Status. Document had a relationship OneToMany with Status, that represented the history of Status the Document had.

So, there was a @NotNull @ManyToOne reference of Document inside Status.

Also, I needed to know the actual Status of Document. So, I needed another relationship, this time @OneToOne, also @NotNull, inside Document.

The problem was: how can I persist both entities the first time if both had a @NotNull reference to the other?

The solution was: remove @NotNull reference from actualStatus reference. This way, it was able to persist both entities.

like image 16
djejaquino Avatar answered Nov 16 '22 09:11

djejaquino