Reputation: 139
First of all, sorry, I cannot explain myself in any better way.
I am programming an example API, I have a POJO (with JPA) called Movie, so in my controller, I want to give it a JSON to insert a Movie.
Movie has a @ManyToOne(optional = false)
property, relating another POJO called Genre
(idGenre
, Name
)
I want to give in a JSON not an object with every property but an id, so:
CONTROLLER
@RequestMapping(value = "/sendMovie", method = RequestMethod.POST)
public void setMovie(@RequestBody Movie movie) {
mRepo.save(movie);
}
Movie
@Entity
public class Movie {
@Id
@Column(name = "ID_MOVIE", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long idMovie;
@Column(name = "NAME")
private String name;
@Column(name = "SYNOPSIS")
private String synopsis;
@Column(name = "POSTER")
private String poster;
@Column(name = "DIRECTOR")
private String director;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idGenre")
@JsonIdentityReference(alwaysAsId = true)
@ManyToOne(optional = false)
@JoinColumn(name = "ID_GENRE", referencedColumnName = "ID_GENRE")
private Genre genre;
JSON I want to use
{
"name": "MATRIX",
"idGenre": 3,
"synopsis": "NEO DOING THINGS",
"poster": "matrix.jpg",
"director": "WACHOWSKIS"
}
Is there possibility to achieve that?
Upvotes: 0
Views: 200
Reputation: 10147
You did put the JsonIdentity...
annotations at the wrong place.
You need to put these annotations on your @Genre
class:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idGenre")
@JsonIdentityReference(alwaysAsId = true)
public class Genre {
@Id
@Column(...)
private Long idGenre;
//....
}
and remove these annotations from the property Genre genre
in your Movie
class.
You also need to tell Jackson with @JsonProperty("idGenre")
that you want this property
serialized with name "idGenre"
.
@ManyToOne(optional = false)
@JoinColumn(name = "ID_GENRE", referencedColumnName = "ID_GENRE")
@JsonProperty("idGenre")
private Genre genre;
Then the JSON output will be something like this:
{
"name": "MATRIX",
"synopsis": "NEO DOING THINGS",
"poster": "matrix.jpg",
"director": "WACHOWSKIS",
"idGenre": 3
}
Upvotes: 2