简体   繁体   中英

How to mark a field as not to be expanded by JAXB in JAXRS

I have 2 classes as follows:

@XmlRootElement
@PersistenceCapable(detachable="true")
public class User {

    @Persistent(primaryKey="true", valueStrategy=IdGeneratorStrategy.IDENTITY)
    private Long id;

    private String firstname;
    private String lastname;
    private UserDetails userDetails;
...
}

and

@XmlRootElement
@PersistenceCapable(detachable="true")
public class UserDetails {
    private String streetaddress;
    private String address;
    private String city;
    private int pincode;
    private Date dateofbirth;
...
}

I need to retrieve the user objects only, without having the userdetails in one JAXRS function, and both the user object and its attached userdetails object in another as shown.

//UserManager.java
public List<User> getUsers() {
    javax.jdo.Query q = pm.newQuery("SELECT FROM "+ User.class.getName());
    List<User> users = (List<User>) q.execute();
    return users;
}

and the JAXRS service:

@GET
@Produces({MediaType.APPLICATION_JSON})  
public List<User> getUsers() {        //Retrieves all users and user details
    UserManager um=new UserManager(); //working perfectly
    return um.getUsers();
}

@GET
@Produces({MediaType.APPLICATION_JSON})  
public List<User> getUsers() {        //should retrieve user only, but how?
    UserManager um=new UserManager();
    return ?????
}

How can I prevent the UserDetails object from being expanded by JAXRS and JAXB for the second function???

if you are returning same type from both functions then jaxb can't help you in hiding information from one method and showing in second.

there are two ways to achieve this:

1) either return different user object fron second function which does not aggregate userdetails. 2) in second function write a query that does not populate user details data.

You can combine the use of JDO fetch plans and lifecycle policies.

Create a named fetch group for your userDetails eg

@FetchGroup(name="details", members={@Persistent(name="userDetails")})

When you want everything, you don't have to do anything technically because JAXB is navigating the graph, but to be complete you'd specify this fetch plan and make your returned object transient following the fetch plan, eg:

pm.getFetchPlan().addGroup("details");
[...]
return (List<User>)pm.makeTransientAll(um.getUsers(), true); // use fetch plan

When you want the shallow fetch, use the default fetch plan and make your returned object transient, eg:

return (List<User>)pm.makeTransientAll(um.getUsers(), true); // use fetch plan

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM