1

I have two entities that sent via rest service with Json format and i want to save both of them in one transaction that jpa cascade ALL provided but in Spring Data Rest i can only POST one entity. i searched a lot and their solution was i should post first entity and then second entity after that i shouold provide a link between them with PUT (like this https://hellokoding.com/restful-api-example-with-spring-boot-spring-data-rest-one-to-many-relationship-and-mysql/ ). that is work but i need sent just one DTO in one transaction, in this solution entities persist separately and if one of them fails to commit i can not rollback others. Below are my entities:

@Entity
@Table(name = "RESTAURANT")
public class Restaurant extends BaseEntity {

private String name;
private Address address;

public Restaurant() {
}

@Column(name = "NAME", nullable = false, unique = true)
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}


@OneToOne(fetch = FetchType.LAZY, mappedBy = "restaurant", cascade = CascadeType.ALL)
public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    if (address == null) {
        if (this.address != null) {
            this.address.setRestaurant(null);
        }
    } else {
        address.setRestaurant(this);
    }
    this.address = address;
}
}

and

@Entity
@Table(name = "ADDRESS")
public class Address extends BaseEntity {

private String title;
private Restaurant restaurant;

@Column(name = "TITLE")
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "RESTAURANT_ID")
public Restaurant getRestaurant() {
    return restaurant;
}

public void setRestaurant(Restaurant restaurant) {
    this.restaurant = restaurant;
}

}

And when POST to http://localhost:8088/restaurants with below JSON:

{
"name":"restaurant name",
"address":{
    "title":"asli"
}

}

expected saving cascade but address disappeared in back end. Also i don't use RestController in another file i want spring data jpa provide all rest services.

Fazel Farnia
  • 161
  • 2
  • 8
  • I am not sure this is the cause of your issue but it is certainly an issue given you have a bidirectional relationship and both sides need to be set: https://stackoverflow.com/questions/30464782/how-to-maintain-bi-directional-relationships-with-spring-data-rest-and-jpa – Alan Hay Feb 20 '20 at 08:59
  • I read that post but as i said i can not see associations that depend to main entity when using spring data rest.so i do not have any problem with spring data jpa that works properly in complex entities by cascading. i mean when PUT an entity with their relations when come to controller their children are null. – Fazel Farnia Feb 24 '20 at 19:58

0 Answers0