Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post an entity with Spring Data REST which has relations

I'm using Spring Data Rest. I have a problem trying to POST an object with association(e.g. address is a field in my entity that is mapped as many to one).

The question is, what format should we use to connect our new entity with its relations. I saw several answers and tried all options that I found. Unfortunately, all of them don't work for me. The following error happens:

Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "ADDRESS_ID"; SQL statement:

JSON that I tried:

{
"name": "test",
"email": "test@email",
"address": "http://localhost:8080/MyApp/address/1"
}

Also tried these:

"address": {"id":"http://localhost:8080/MyApp/address/1"}

And this:

"address":{"id":1}

And even this:

"address": {
"href": "http://localhost:8080/MyApp/address/1"
}

Is there a way to do this, or only writing own implementation of controller for POST? Thanks!

like image 740
dvelopp Avatar asked Jun 12 '17 10:06

dvelopp


People also ask

What is difference between JpaRepository and CrudRepository?

CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.

What does @table do in spring?

The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table.


1 Answers

If you have a model like this:

@Entity
public class User {
    //..
    private String name;

    @OneToMany(mappedBy = "user")
    private Set<Address> addresses = new HashSet<>();
    //..
}

@Entity
public class Address {
    //..
    @ManyToOne
    private User user;
    //..
}

then you can POST a new User with its addresses like this:

POST http://localhost:8080/api/users
{
    "name" : "user1",
    "addresses" : [
        "http://localhost:8080/api/addresses/1",
        "http://localhost:8080/api/addresses/2"
        ]
}

Before POST a new User, addresses ID#1 and ID#2 must be already persisted.

like image 178
Cepr0 Avatar answered Oct 12 '22 13:10

Cepr0