我有以下模型类:
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "iduser")
private Integer idUser;
@Basic(optional = false)
@Column(name = "passwd")
private String passwd;
@JoinColumn(name = "idusersgroup", referencedColumnName = "idusersgroup")
@ManyToOne(optional = true)
private UsersGroups idUsersGroup;
.
.
.
}
public class UsersGroups implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idusersgroup")
private Integer idUsersGroup;
@Basic(optional = false)
@Column(name = "description")
private String description;
.
.
.
}
所以我写了一个服务来访问Users
数据:
@POST
@Consumes("application/json")
public Response createUser(Users user) {
Users login;
UsersDAO u = new UsersDAO();
if(user.getLogin() == null || user.getDescription() == null ||
user.getNif() == 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();
}
问题是我不想将关系的参数作为JSON中的对象传递,而只是传递其id。像这样:
{
"login": "admin2",
"passwd": "12345",
"idusersgroup": 1
}
但是通过此实现,idUsersGroup
应该是UsersGroup
的实例,而不是其ID。
实现这一目标的最佳方法是什么?改变模型类中关系的实现方式?将JSON对象的格式更改为将idUsersGroup
作为嵌套对象更改?还有其他选择吗?我是新手,并且仍然了解如何在每种情况下定义关系
答案 0 :(得分:1)
使用JPA / Hibernate,我们希望自己处理关系。所以基本上你需要做的就是查找UserGroup
(无论你如何查找),然后在UserGroup
上设置User
。这样,UserGroup
User
个ID
UserGroupDao ugDao = new UserGroupDao();
UserGroup uGroup = ugDao.findOne(user.getIdusersgroup());
user.setIdUsersGroup(uGroup);
u.addUser(user);