I am using JPA's Entity Beans to represent the data inside my database. This already works quite good, but I have got a problem outputting an N-M relationship that is represented by an extra entity.
Those are my entities:
@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;
}
The problem is that an Event holds an Employee and vice versa. Whenever I want to output one of those objects as a JSON (via JAX-RS) it gets stuck in a loop.
/*
* 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);
}
Is there any way in which I can reduce the output to something like this, when printing the object, so that it does not end in a loop:
{
"id: 1,
"name: "Event1",
"employees" :
[
{
[
"id" : 1;
"firstName" : "John",
"lastName" : "Doe"
],
"status": "true"
}
]
}