I have 2 Entities: User and UserAlias. User have composite PK. I have some questions:
How to parse JSON in spring MVC controller to populate User and UserPK objects, for example with this data:
{ "id" : 1, "name" : "newUser", "aliases": [ "alias1", "alias2", "alias3" ] }
If i writepublic void createUser(@RequestBody User user)
i will obviously get an exception.
How can i write my controller method to parse data to both entities?
- For now i'm using a DTO object to parse JSON with @RequestBody and populate models. But i'm not sure this is good way to do this task.
User.java
@Entity
@Table(name = "user")
public class User {
@EmbeddedId
private UserPK userid;
public User(){}
public User(UserPK userid) {
this.userid = userid;
this.aliases = aliases;
}
@OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
public List<UserAlias> aliases = new ArrayList<>();
}
UserPK.java
@Embeddable
public class UserPK implements Serializable {
@NotNull
@Column(name = "id")
private Integer id;
@NotNull
@Column(name = "name")
private String name;
public UserPK(){};
public UserPK(Integer id, String name){
this.id = id;
this.name = name;
}
}
UserAlias.java
@Entity
@Table(name = "user_alias")
public class UserAlias {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "user_alias")
private String userAlias;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(
referencedColumnName = "id"),
@JoinColumn(
referencedColumnName = "name")
})
@JsonIgnore
public User user;
public UserAlias(){}
public UserAlias(String userAlias) {
this.userAlias = userAlias;
}
1. First question:
How to parse JSON in spring MVC controller to populate User and UserPK objects?
Well your JSON have to be matching your entity structure, so you need to have a UserId
object, inside your User
object in order to match the expected structure. In your case the JSON you are sharing won't match that, and will throw an Exception when passed to the Spring Controller.
This is what you will need as JSON:
{ "userid": {"id" : 1, "name" : "newUser"}, "aliases": [ "alias1", "alias2", "alias3" ] }
2. Second question:
For now i'm using a DTO object to parse JSON with @RequestBody and populate models. But i'm not sure this is good way to do this task?
Yes it's a good way to use DTO
especially if you won't to keep the same JSON
structure you are using right now, and using the passed DTO
you can construct your User
object respectively.
Using @JsonUnwrapped
annotation:
If you want to avoid the use of a DTO
, you can just use Jackson's @JsonUnwrapped
annotation, with your userId
field, this way its properties will be serialized as properties of the User
class and your first JSON
will be accepted.