1

I am new in JPA, so excuse me if my question seems basic. I have an entity called User, which is related to a list of other entities like follow:

@OneToMany(cascade = CascadeType.ALL , mappedBy = "user")
private List<session> sessionList;

In a controller class, I defined a find method in a RESTFull manner like follow:

@GET
@Path("/Users")
@Produces("application/json")
public List<UserDevice> findAllUsers()
{
    return em.createQuery("SELECT u FROM User u").getResultList();
}

The returned result contains all the sessions of the users which is normal, but make the result huge though I just want to retrieve the basic information of the users (all the simple columns). My question is: is it possible to ignore the related entities and just keep the columns of the actual entity? Thank you very much

Rami
  • 8,044
  • 18
  • 66
  • 108

1 Answers1

2

Unless you explicitely map the association as eagerly loaded (using @OneToMany(fetch = FetchType.EAGER)), the above query should only return the fields of the users, and should not load their sessionList.

If the sessions are loaded, then the association is marked as eagerly loaded, or you load them lazily by calling a method of the List<Session>.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Perhaps the @Produces("application/json") uses reflection to serialize the object with all its relations to json, and thus initializes the lazy collection? – Rasmus Franke Jun 25 '12 at 18:32
  • Thanks Rasmus and JB, Thank you very much for your answer, It working now after that I added FetchType.LAZY to the @OneToMany annotation :) – Rami Jun 26 '12 at 09:11
  • Rasmus, can you please explain what is reflection? Thank you – Rami Jun 26 '12 at 11:00
  • Thank you JB I will have a look to it – Rami Jun 26 '12 at 11:19
  • It seems that my problem now is with @ManyToOne relation, the lazy fetch of these relations is not working. I am searching for a solution of this problem but so far nothing is working. any suggestion? – Rami Jun 26 '12 at 11:41
  • *"Nothing is working"* is the poorest description you might give of a problem. Ask another question where you explain what you want to do, how you do it, what you expect it does, and what it does instead. – JB Nizet Jun 26 '12 at 11:43
  • OK JB, excuse me! I will post a new question and describe more in details the problem... maybe I do not understand well my problem that is why my description is poor. – Rami Jun 26 '12 at 12:18
  • Ok, adding @XmlTransient as annotation to the method that gets the List resolve the problem. Apparently I have a name collision in the Session class. In this class I have a field called user and a getter of this field, so I guess there is a collision between this field and the get property: getSessionList(). – Rami Jun 26 '12 at 15:29