我让它工作......有点。除了打印出Json时,它会打印出很多重复的代码。我怀疑这与它的编组方式有关。无论如何,这是我的代码:
用户.java
@XmlRootElement(name="user")
@Entity
@Table(name="users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@XmlElement(required=true)
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@XmlElement(required=true)
@Column(name="username", nullable=false)
private String userName;
@XmlElement(required=true)
@Column(name="phoneid", nullable=false)
private String phoneid;
@XmlTransient
@ManyToMany(
cascade={CascadeType.ALL},
mappedBy="voters",
targetEntity=Vote.class,
fetch=FetchType.EAGER
)
private List<Vote> votes = new ArrayList<Vote>();
投票.java
@XmlRootElement(name="vote")
@Entity
@Table(name="votes")
public class Vote implements Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(required=true)
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", nullable=false)
private int id;
@XmlElement(required=true)
@Column(name="name", nullable=false)
private String name;
@XmlElement(required=true)
@Column(name="max", nullable=false)
private int max;
@XmlElement(required=true)
@Column(name="current", nullable=false)
private int current;
@XmlElement(required=true)
@Column(name="is_simple", nullable=false)
private int isSimple;
@XmlTransient
@ManyToMany(cascade = {CascadeType.ALL}, targetEntity=User.class, fetch=FetchType.EAGER)
@JoinTable(name = "vote_user",
joinColumns = {@JoinColumn(name = "vote_id")},
inverseJoinColumns = {@JoinColumn(name = "user_id")}
)
private List<User> voters = new ArrayList<User>();
GetRestfulVote.java
@Path("/votes")
public class GetRestfulVote {
@EJB
VoteBeanInterface bean;
@GET
@Path("/{userid}")
@Produces(MediaType.APPLICATION_JSON)
public List<Vote> getVotesJson(@PathParam("userid") String userId) {
//Will be getting using the user id to be able to set a flag if the calling user voted in it
List<Vote> listOfVotes = bean.getVotes();
return listOfVotes;
}
}
Vote
现在,从我的代码中可以很明显地看出,我和User
类之间存在多对多的关系。我相信这就是问题发生的地方。但问题是我不知道如何防止它从“jsonification”过程中被忽略。更重要的是,我怎样才能强制它只将拥有的类列表(Votes
)变成 Json。任何帮助和澄清将不胜感激!