I have two Entities with bidirectional relation OtM <-> MtO. I also use cascade PERSIST because I would like to persist the data at once.
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne(cascade = CascadeType.PERSIST)
private Author author;
}
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String title; //mr, mrs
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books;
}
I have created BookRepository at first and exposed it with Spring Data REST.
@RepositoryRestResource
public interface BookRepository extends JpaRepository<Book, Long>{
}
When I sent POST request with JSON:
{
"title": "Some title",
"author": {
"title": "Mr",
"name": "John Doe"
}
}
everything works and both book and author entities are persisted. Now I wanted to expose data about authors so I've added another Repository:
@RepositoryRestResource
public interface AuthorRepository extends JpaRepository<Author, Long> {
}
Now when I send the same JSON, the book entity is persisted, but author entity is not. What is more, the book title is now "Mr".
I do not understand this weird behaviour. Why with single repository everything works fine, but after adding another one, Spring is not only not persisting related author entity, but it is taking the wrong "title" field from JSON that I've sent?
Is there any way to persist the data with single request or I always have to persist author first and then persist the book with HAL format like "author": "http://.../createdAuthorId"?
See the office guide. Here an example:
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne(cascade = CascadeType.PERSIST)
@RestResource(exported = false)
private Author author;
}
I add @RestResource(exported = false) to the author property.
The Author entity should not be modified.
You can cascade-persist author like this:
{
"title": "Some title",
"author": {
"title": "Mr",
"name": "John Doe"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With