Json,JPA,ManytoOne和OneToMany =>递归

时间:2015-06-02 06:50:23

标签: java json jpa eclipselink

我试图阅读有关此主题的所有问题,但仍有一些我不知道的事情。

我的问题是:两个表KIDS和PARENT正在相互调用

我有一个EJB要求父母带有id, - 我(我认为)在需要时使用@OneToMany(mappedBy =" parent")。结果可能会更好:当要求父母(带有身份证)时,会看到有一个孩子接受要求孩子的父母......(在一个几乎永无止境的故事中:)

JSON OUTPUT

{
  "parentsid": 1,
  ...
  "parentsusername": null,
  "calendars": [],
  "kids": [
    {
      "kidsid": 2,
        ...
      "parent": {
        "parentsid": 1,
        ...
        "calendars": [],
        "kids": [
          {
            "kidsid": 2,               
            "calendars": [],
            "checkins": [],
            "parent": {
              "parentsid": 1,                 
              "calendars": [],
              "kids": [
                {
                  "kidsid": 2,                     
                  "calendars": [],    
                 .....

课程 我有一个无状态Bean呼叫:

@Stateless
@LocalBean
@Path("/checkin")
public class CheckinService {

 @PersistenceContext(unitName="chkin",type=PersistenceContextType.TRANSACTION)
 EntityManager entityManager;

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{id}")    
public Parent read(@PathParam("id") int id) {
    Parent parent = entityManager.find(Parent.class, id);        
    return parent;
}

使用

按以下方式制作实体类
/**
 * The persistent class for the KIDS database table.
 */
@Entity
@Table(name="KIDS")
@NamedQuery(name="Kid.findAll", query="SELECT k FROM Kid k")
public class Kid implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="KIDSID")
    private int kidsid;

    //bi-directional many-to-one association to Calendar
    @OneToMany(mappedBy="kid")
    private List<Calendar> calendars;

    //bi-directional many-to-one association to Checkin
    @OneToMany(mappedBy="kid")
    private List<Checkin> checkins;

    //bi-directional many-to-one association to Parent
    @ManyToOne             **// <=============**
    @JoinColumn(name="parentsId")
    private Parent parent;
}

父母的实体电话:

@Entity
@Table(name="PARENTS")
@NamedQuery(name="Parent.findAll", query="SELECT p FROM Parent p")
public class Parent implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="PARENTSID")
    private int parentsid;

    ...

    //bi-directional many-to-one association to Calendar
    @OneToMany(mappedBy="parent")
    private List<Calendar> calendars;

    //bi-directional many-to-one association to Kid
    @OneToMany(mappedBy="parent") **// <=============**
    private List<Kid> kids;

数据库看起来像这样: 两个名为PARENTS和一个KIDS的数据库表有一个从PARENTS到KIDS的onetomany,带有一个名为FK-KIDS_parentsID的foreng键

PARENTS ==========FK_KIDS_parentsId==========< KIDS
(PK) PARENTSID                                 (PK) KIDSID
                                               (FK) parentsId

堆栈跟踪

[error occurred during error reporting (printing native stack), id 0xc0000005]

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  sun.nio.ch.WindowsSelectorImpl$SubSelector.poll0(JI[I[I[IJ)I+0
j  sun.nio.ch.WindowsSelectorImpl$SubSelector.poll()I+43
j  sun.nio.ch.WindowsSelectorImpl$SubSelector.access$400(Lsun/nio/ch/WindowsSelectorImpl$SubSelector;)I+1
j  sun.nio.ch.WindowsSelectorImpl.doSelect(J)I+63
j  sun.nio.ch.SelectorImpl.lockAndDoSelect(J)I+37
j  sun.nio.ch.SelectorImpl.select(J)I+30
j  sun.nio.ch.SelectorImpl.select()I+2
j  org.xnio.nio.SelectorUtils.await(Lorg/xnio/nio/NioXnio;Ljava/nio/channels/SelectableChannel;I)V+23
j  org.xnio.nio.NioSocketConduit.awaitWritable()V+26
j  org.xnio.conduits.AbstractSinkConduit.awaitWritable()V+7
j  io.undertow.conduits.ChunkedStreamSinkConduit.awaitWritable()V+7
j  org.xnio.conduits.ConduitStreamSinkChannel.awaitWritable()V+4
j  io.undertow.channels.DetachableStreamSinkChannel.awaitWritable()V+20
j  io.undertow.server.HttpServerExchange$WriteDispatchChannel.awaitWritable()V+20
j  org.xnio.channels.Channels.writeBlocking(Ljava/nio/channels/GatheringByteChannel;[Ljava/nio/ByteBuffer;II)J+34
j  io.undertow.servlet.spec.ServletOutputStreamImpl.write([BII)V+311
j  org.jboss.resteasy.plugins.server.servlet.HttpServletResponseWrapper$DeferredOutputStream.write([BII)V+15
j  org.jboss.resteasy.util.CommitHeaderOutputStream.write([BII)V+11
j  com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer()V+24
j  com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeBytes([B)V+17
J 1041 C2 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V (185 bytes) @ 0x0000000002979c78 [0x00000000029796c0+0x5b8]
j  com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+41
J 1041 C2 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V (185 bytes) @ 0x0000000002979b78 [0x00000000029796c0+0x4b8]
j  com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+41
j  com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(Ljava/util/List;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+163
j  com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+7
j  com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+34
J 1041 C2 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V (185 bytes) @ 0x0000000002979b78 [0x00000000029796c0+0x4b8]
j  com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+41
J 1041 C2 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V (185 bytes) @ 0x0000000002979b78 [0x00000000029796c0+0x4b8]
j  com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+41
j  com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(Ljava/util/List;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+163
j  com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+7
j  com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+34
J 1041 C2 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V (185 bytes) @ 0x0000000002979b78 [0x00000000029796c0+0x4b8]
j  com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+41
J 1041 C2 com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V (185 bytes) @ 0x0000000002979b78 [0x00000000029796c0+0x4b8]
j  com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V+41

3 个答案:

答案 0 :(得分:2)

正如评论所指出的那样,这似乎不是一个JPA问题,因为它是一个JSON序列化问题。幸运的是,杰克逊提供several annotations来处理这种情况。

在父级上使用@JsonManagedReference,在孩子上使用@JsonBackReference,您可能想尝试使用@JsonIdentityInfo

这里有一些more reading您可能会觉得有帮助。

答案 1 :(得分:2)

这是循环依赖和JSON序列化的问题,解决这个问题的一个简单方法是在两个类上使用@JsonIdentityInfo,你应该有这样的东西:

@Entity
@Table(name="KIDS")
@NamedQuery(name="Kid.findAll", query="SELECT k FROM Kid k")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Kid implements Serializable {

@Entity
@Table(name="PARENTS")
@NamedQuery(name="Parent.findAll", query="SELECT p FROM Parent p")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class Parent implements Serializable {

通过这种方式,您可以确保在每个孩子序列化中父母不会被序列化,但您只会获得他的身份。

答案 2 :(得分:0)

@dcsohl谢谢你的帮助, - 我想我现在明白了......

我回到了我的问题,又有了一次。这是JSON recursiv问题。

相反,我正在使用@XmlTransient我找到了另一种处理这个问题的方法, - XMLTransient的问题是你没有得到id, - 所以我正在使用:@XmlIDREF和{{ 3}}解决这个问题。

@Entity
@Table(name="PARENTS")
@NamedQuery(name="Parent.findAll", query="SELECT p FROM Parent p")
public class Parent implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="PARENTSID")
    @XmlAttribute @XmlID private int parentsid;

    ...

    @ManyToMany
    @JoinTable(name="PARENTS_KIDS",joinColumns=@JoinColumn(name ="PARENT_FK"), inverseJoinColumns=@JoinColumn(name = "KID_FK"))     
    private List<Kid> kids;

班级孩子

@Entity
@Table(name="KIDS")
@NamedQueries({
@NamedQuery(name="Kid.findAll", query="SELECT k FROM Kid k"),
}) 
@XmlRootElement
public class Kid implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="KIDSID")
private int kidsid;

@ManyToMany(mappedBy="kids")
@XmlAttribute @XmlIDREF private List<Parent> parents;

....
}

它有效:D