I have two classes:
public class A implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "fieldID")
private Collection<B> bCollection;
...
public Collection<B> getBCollection()
{
return bCollection;
}
public void setBCollection(Collection<B> bCollection)
{
this.bCollection = bCollection;
}
}
public class B implements Serializable {
...
@JoinColumn(name = "aID", referencedColumnName = "id")
@ManyToOne(optional = false)
private A aID;
...
@XmlTransient
public A getAID() {
return aID;
}
public void setAID(A aID) {
this.aID= aID;
}
}
I was always using A
class - it is working as inteded, but now, I want to use B
class in RESTful GET
method. However, when I try to do that, @XmlTransient
prevents showing A
field. Is it possible to use @XmlTransient
on A
class, when I am using B
class and to use it on B
class, when I am using A
class?
One easy solution is to include https://eclipse.org/eclipselink/moxy.php and start using @XmlInverseReference
annotation for bi-directional dependencies. http://eclipse.org/eclipselink/api/2.2/org/eclipse/persistence/oxm/annotations/XmlInverseReference.html.
If it is not possible, please provide more information which JAXB/JAX-RS implementation you are using to be able to come up with some more concrete solution for your problem.
In general the idea is to control serialization process and decide how certain objects/fields are serialized and if those should be serialized at all. It can be achieved for example with following strategies:
Serialize class B not as a whole object, but rather just as a String representation of it, when class A is serialized. For example using @XmlAttribute @XmlIDREF
.
Control serialization process by setting up, for example, some kind of Filter/Exclusion (depending on what does your JAX-RS implementation provide):
ExclusionStrategy() {
public boolean shouldSkipClass(Class<?> clazz) {
return (clazz == B.class);
}
/**
* Custom field exclusion goes here
*/
public boolean shouldSkipField(FieldAttributes f) {
return false;
}
}