For implementing a REST API in Java, I'm using: - Jersey JAX-RS Framework - Genson parser - Tomcat8 server - Hibernate
I have this method in a service class:
@POST
@Consumes("application/json")
public Response createUser(Users user) {
UsersDAO u = new UsersDAO();
if(user.getLogin() == null || user.getPasswd() == null)
return Response.status(Response.Status.BAD_REQUEST).entity("Missing information").build();
try{
u.addUser(user);
}catch(HibernateException e){
return Response.status(Response.Status.BAD_REQUEST).entity("User already exists").build();
}
return Response.status(Response.Status.CREATED).build();
}
The Users
class:
public class Users implements Serializable {
@Basic(optional = false)
@Column(name = "passwd")
private String passwd;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "iduser")
private Integer idUser;
@Basic(optional = false)
@Column(name = "login")
private String login;
@JoinColumn(name = "idusersgroup", referencedColumnName = "idusersgroup")
@ManyToOne(optional = true)
private UsersGroups idUsersGroup;
@Transient
private int idGroup;
.
.
.
}
As you can see, I created the idGroup
field just to store the id of the UsersGroups
object related, so if I want to add the group in the moment of the user creation, I'll just have to include its id in the JSON instead of the UsersGroups
object (the relationship is optional, a user can belong to a group or not). The problem is Genson is not adding this field to the Users
object when consumes the JSON:
{
"login": "admin1",
"passwd": "12345",
"idgroup": 3
}
If I POST this JSON and then access to the user.getIdGroup()
, it returns 0, so I assume that idGroup
field isn't being consumed. Could the @Transient
annotation has something to do with this issue? Any idea on how to solve it? If the problem is Genson and there's any solution using another JSON parser (like Jackson), I could consider a switch