1

I want to run a query, but the results should be read only. And they might need a refresh, and I don't want to refresh each element in the list. I'd rather re-execute the query. Thus I want all the results to be detached. What I currently do is

List<Ent> lst = (List<Ent>)em.createQuery("FROM Ent").getResultList();
for (Ent l:lst) em.detach(l);

But it seems wrong to me.

Any better way to do that?

Elazar Leibovich
  • 32,750
  • 33
  • 122
  • 169

3 Answers3

3

It seems that you do not want the returned objects to be managed by the persistence context .You can consider to use StatelessSession as everything returned using StatelessSession are in the detached state and do not managed by the persistence context

StatelessSession session = sessionFactory.openStatelessSession();
List<Ent> lst  = session.createQuery("FROM DeviceTree").getResultList(); //All the returned Ent are in the detached state

Note that the StatelessSession does not implement a first-level cache , second-level or query cache.Everything you do results in immediate SQL operations . You can think it just like using plain JDBC, except that you get the benefit from mapped persistent classes .


Reference

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • It's not exactly what I want, since I could use, say, query cache. But it's good more or less. Is there a JPA equivalent? – Elazar Leibovich Jul 25 '11 at 07:18
  • I am afraid there are no JPA equivalent, but I am not 100% sure. – Ken Chan Jul 25 '11 at 07:24
  • BTW, this JPA is surely confusing. You expect `em.find(Ent.class,1);em.createQuery("UPDATE Ent SET data=17").executeUpdate();assertEquals(17,em.createQuery("FROM Ent WHERE id=1").getResultList().get(0).getData());` to pass. The fact that the entity is cached and not refetched from the DB is not completely clear. – Elazar Leibovich Jul 25 '11 at 07:44
0

Maybe Hibernate doesn´t support the detach() method? You could copy your entities to a new object type and return these detached entities to the caller.

There are several similar questions about this topic here on StackOverflow: Detach an entity from JPA/EJB3 persistence context

Community
  • 1
  • 1
Kai
  • 38,985
  • 14
  • 88
  • 103
-2

Make the list as unModifieable list

YOur code will be

List<Ent> lst = (List<Ent>)em.createQuery("FROM DeviceTree").getResultList();
lst =(List) Collections.unmodifiableCollection(lst );

Sample

 List arl = new ArrayList();
        arl.add("sk");
        arl.add("sk2");
        System.out.println("...."+arl);
        arl =(List) Collections.unmodifiableCollection(arl);
try{
        arl.add("sk3");  // it will give exception
}catch(exception ex
{ex.printStackTrace();}     System.out.println("...."+arl);