如何输出N-M关系作为JSON?

时间:2017-12-27 16:49:18

标签: java json jpa jackson jax-rs

我正在使用JPA的Entity Beans来表示我的数据库中的数据。这已经很好用了,但是输出一个由额外实体表示的N-M关系时遇到了问题。

这些是我的实体:

@Entity
@Table(name = "employee", schema = "klk")
public class Employee implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;
    @Basic
    @Column(name = "firstName", nullable = false)
    private String firstName;
    @Basic
    @Column(name = "lastName", nullable = false)
    private String lastName;
    @Basic

    @OneToMany(mappedBy="employeeId",cascade=CascadeType.REMOVE, orphanRemoval = true)
    private Set<EventEmployee> events = new HashSet<EventEmployee>();
}

@Entity
@Table(name = "event", schema = "klk")
public class Event implements Serializable{
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;
    @Basic
    @Column(name = "name", nullable = false)
    private String name;

    @OneToMany(mappedBy="eventId",cascade=CascadeType.REMOVE, orphanRemoval = true)
    private Set<EventEmployee> employees = new HashSet<EventEmployee>();

}

@Entity
@IdClass(EventEmployeeKey.class)
@Table(name = "eventemployee", schema = "klk")
public class EventEmployee implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @ManyToOne
    @JoinColumn(name = "eventId", nullable=false, updatable=false)
    private Event eventId;

    @Id
    @ManyToOne
    @JoinColumn(name = "employeeId", nullable=false, updatable=false)
    private Employee employeeId;

    @Basic
    @Column(name = "status", nullable=false)
    private boolean status = false;
}

问题是,一个事件持有一个员工,反之亦然。每当我想输出其中一个对象作为JSON(通过JAX-RS)时,它就会陷入循环。

/* 
 * Get a specific Event by the ID.
 * @param id - the id of the Event.
 * @return Returns a JSON which contains data of the corresponding Event.
 */
@GET
@Path("/getEvent/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured
public Event getEvent(@PathParam("id") int id) {
    return dm.getEventById(id);
}

有什么方法可以在打印对象时将输出减少到这样的程度,这样它就不会以循环结束:

{
    "id: 1,
    "name: "Event1",
    "employees" : 
        [
            {
                [
                    "id" : 1;
                    "firstName" : "John",
                    "lastName" : "Doe"
                ],
                "status": "true"
            }   
        ]
}

0 个答案:

没有答案