问题
I have a few many to many relationships in my data model. I have been trying to use JAX=B to get XML representations of the data models, however I have read that for one to many relationships an:
@XmlInverseReference
is needed for the inverse side of the mapping. I believe this is for using different fetch types (ie. LAZY and EAGER). I am unsure of exactly how this annotation works. Does it use back pointers to ensure that data is not fetched when it is specified on certain fields? I also do not know if I need to annotate my many to many relationship with the above annotation or not.
Here is the user class that has a many to many relationship with itself, ie. a user can be friends with many other users. Should I annotate the getter with an @XmlInverseReference?
@Entity
@Table(name = "users")
public class User implements Serializable {
...
// bi-directional many-to-many association to User
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.REFRESH })
@JoinTable(name = "friends", joinColumns = { @JoinColumn(name = "uid") }, inverseJoinColumns = { @JoinColumn(name = "frienduId") })
private List<User> friends;
/**
* @return
*
* gets the list of users this user is friends with
*/
public List<User> getFriends() {
return this.friends;
}
/**
* @param friendsList
*
* sets the users friends list
*/
public void setFriends(List<User> friendsList) {
this.friends = friendsList;
}
Any help or guidance is much appreciated.
回答1:
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
@XmlInverseReference
is a EclipseLink JAXB (MOXy) extension that enables you to map bidirectional relationships:
- http://blog.bdoughan.com/2010/07/jpa-entities-to-xml-bidirectional.html
- http://blog.bdoughan.com/2013/03/moxys-xmlinversereference-is-now-truly.html
@XmlInverseReference
serves two roles:
- During marshalling it prevents an infinite loop from occurring. If a bidirectional relationship exists between
Foo
andBar
, it will marshalFoo
thenBar
and then it will stop before trying to marshalFoo
again. - During unmarshalling it will populate the back pointer.
来源:https://stackoverflow.com/questions/17005039/jax-b-xml-inverse-reference-with-many-to-many-relationship