问题
I am using Angularjs, Spring jpa repository, hibernate. The problem is "Unable to save the id of the Customer in the order table." table names: Order, CustomerGlobal reference col name for Customer in Order table is customerGlobal_id. Order belongs to a Customer. Order table has a customerGlobal_id field.
In the Entity (Order), I have defined
@ManyToOne(optional = false) @JsonIgnore
CustomerGlobal customerGlobal;
Order belongs to one Customer. If I specify a JoinColumn, hibernate is generating the column in the database. So, I think there is no issue there. I have added Getter and Setter for the customerGlobal field.
I am using JPA repository, the interface is defined as follows:
public interface OrderRepo extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {
...
}
I am assuming that this would work fine too.
Here is the relevant part of the html:
<select ng-options="convertToInt(customer.id) as customer.name for customer in c" class="form-control " name="customerGlobal" ng-model="req.customerGlobal" required></select>
This is part of a form which gets saved from the associated controller. The values for c are obtained by get request on load.
[{"id":1,"name":"XYZ","contactPerson":"ABC","mobile":"1111111111","email":"abc@adef.com",}]
This seems to be working fine. I get a dropdown list of the customers in the table.
When I save the form, customerGlobal_id and other field values are sent via POST but the customerGlobal_id does not get saved to the database.
This does not seem to be a very specific problem. This is a basic many-to-one relationship that is not getting saved. I am not completely familiar with Angularjs. So please help me out with this. Thanks in advance.
回答1:
In order to save a relationship with spring rest, you shouldn't use the id of the entity, but the reference url of the entity. So let's say that you have a Car
entity that has an association with a Make
entity, and you want to set the make of the car. Here is what you should do:
Step 1. get the Make
entity:
-get a specific `Make`: localhost:8080/makes/1
-get a a list of `Make`: localhost:8080/makes
and select the one you want:
{
"name" : "Toyota",
"country" : "Japan",
"_links" : {
"self" : {
"href" : "http://localhost:8080/makes/1"
}
}
Step 2. Now insert / update a Car
like this:
POST/PUT http://localhost:8080/cars/123
{
"model" : "Corolla",
"year" : "2006",
"hp" : 95,
"make" : "http://localhost:8080/makes/1"
}
and NOT like this:
{
"model" : "Corolla",
"year" : "2006",
"hp" : 95,
"make" : 1
}
Spring Data Rest understands the reference url of the entity.
来源:https://stackoverflow.com/questions/33603168/angularjs-spring-jpa-repository-many-to-one-field-is-not-saving