我正在使用Netbeans 7.4在Glassfish 4.0上开发典型的Java EE 7应用程序。我有一组具有各种关系的JPA实体。因为这可能是一个众所周知的问题,当我尝试使用JAX-RS服务与另一个人的双向关系揭露实体时,我面临一个问题(很可能是由序列化循环引起的)。
我已经搜索了很多解决方案。显然,解决此问题的最干净的方法是使用杰克逊提供商,而不是内置的提供商。但是,这对我来说并不成功。我可能在中间做错了什么,任何提示都将不胜感激。
第一个实体:
@Entity
public class User implements Serializable {
@Id
private long id;
...
@OneToMany(
mappedBy = "owner",
cascade = CascadeType.ALL
)
private List<Playlist> playlists;
...
}
第二实体:
@Entity
public class Playlist {
@Id
@GeneratedValue
private long id;
...
@NotNull
@ManyToOne
private User owner;
...
}
JAX-RS服务:
@Path("/user")
@Stateless
public class UserResource {
@Inject
private UserService userService;
@GET
@Path("/{username}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(@PathParam("username") String username) {
return Response.ok(userService.getUser(username)).build();
}
}
我已经下载并包括最新的杰克逊二进制(Jackson-core-2.3.1.jar)在我的classPath中,当我部署应用程序时,我实际上可以在Glassfish Server日志中看到与Jackson相关的内容。如果返回的用户实体没有任何关联的播放列表,则一切都很好。但是,对于指定用户的一个或多个播放列表,返回了HTTP 500错误,并且在Glassfish Server日志中没有显示任何内容。
事先感谢您的任何帮助。
update
很多来回之后。我仍然无法让杰克逊工作。我搬到了Wildfly(Jboss 8),我无法使用提供的杰克逊版本而不是内置的版本。无论在类路径中添加了哪个版本的杰克逊(有或没有Maven),错误总是指示org.codehaus.jackson。*。
修改您的Playlist
实体类:
@Entity
@JsonIgnoreProperties({"owner"})
public class Playlist {
当您的杰克逊(Jackson)试图序列化具有用户等播放列表的用户等...
查找@mgorgon答案有用。
就我而言,我想和泽西岛一起使用Hibernate
我最终为ID创建了一个字段:
@JsonIgnoreProperties({"parent"}) // this ignores the object for json serialization
public class Object{
private int id;
private AnotherObj parent;
@Transient // this ignores the properties for hibernate mapping, cause we want to use the parent.getId() instead. You may have to put it in your get too
private ind parent_id;
}
然后,在您的objectdao查询中,如果需要从关系中获取它,则可以将父ID定义为parent_id:
类似"来自user_id = parent_id的文件")。
您必须为所有查询做到这一点:
Object.setParent_id(Object.getParent().getId());
因为 parent_id
是瞬态的,冬眠看不见,否则不会列出。
当然,您应该使用懒惰的关系(否则它将加载OBJ)。它之所以起作用,是因为parent_id是对象表的一列,它不需要打电话给父。
当您有很多关系时,这很有用,但是您只需要查询ID。