2
Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(50);
List cats = crit.list();

Will the cats become persistent object in the current session sess?

I checked the API, but it doesn't mention anything. I very worry this, so I hope I can find somewhere officially mention whether the objects will be persistent or not, when I first time using Hibernate's session to load the object, I wasn't aware the object become persistent, and I accidentally amend the value inside the object, the changes flush to database, which cause very big problem for me.

Based on this https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html,

The interface org.hibernate.Criteria represents a query against a particular persistent class.

Does it mean the object returned is persistent? Can I safely change the value inside the object?

If the object will not be persistent, why the API doc having a setReadOnly attribute to control:

Set the read-only/modifiable mode for entities and proxies loaded by this Criteria. This setting overrides the default setting for the persistence context.

I am very confused above this!

Sam YC
  • 10,725
  • 19
  • 102
  • 158

1 Answers1

3

It will become persistent in the current session. If you change object value and flush, it will be saved into a database when transaction ends. Check https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/objectstate.html paragraph 10.4.1. Executing queries:

A query is usually executed by invoking list(). The result of the query will be loaded completely into a collection in memory. Entity instances retrieved by a query are in a persistent state.

Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114
  • This is too bad... Do you know how can I fetch data via Hibernate but they are not in persistent state? This is very dangerous if someone not aware and accidentally flush it... – Sam YC Aug 25 '16 at 08:53
  • Detach object from the session or make session.setDefaultReadOnly(true). Detailed options can be found: http://stackoverflow.com/questions/5800814/is-it-possible-to-detach-hibernate-entity-so-that-changes-to-object-are-not-aut – Justinas Jakavonis Aug 25 '16 at 10:16
  • Thanks for sharing. Too bad, if we always need to detach after data load, it is too troublesome. Using `setDefaultReadOnly` will remove all the persistent object, instead of specific one. Beside this, hibernate don't have any method to load data automatically turn into non-persistent object? – Sam YC Aug 25 '16 at 12:05
  • How about StatelessSession session = sessionFactory.openStatelessSession();? – Justinas Jakavonis Aug 25 '16 at 12:32