Reputation: 33593
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?
Upvotes: 1
Views: 5425
Reputation: 90457
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
Upvotes: 3
Reputation: 39641
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
Upvotes: 0
Reputation:
Make the list as unModifieable list
List<Ent> lst = (List<Ent>)em.createQuery("FROM DeviceTree").getResultList();
lst =(List) Collections.unmodifiableCollection(lst );
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);
Upvotes: -2