简体   繁体   中英

could not initialize proxy - no Session and lazy objects

what is meaning of could not initialize proxy - no Session error?? what meaning of lazy object and why occur??, and how to avoid it without change the hibernate laze property and without using Hibernate.initialize() because that doesn't work for me.

You should mark your method with annotation @Transactional

@Transactional
void method(){
    Entity e = ... (from database);
    e.getLazyField();
}

There are a couple of things here, first of all you appear to asking "what is lazy loading".

If you have an object to be loaded from the database which has a relationship with another object, lazy loading allows you to only load the required object, and the related object will only be loaded when you need it.

The exception you are having is caused by trying to access the related object after the objects have been disconnected from the database session (obviously a db session is required to load them).

There are a few ways we can deal with the situation, the most appropriate will entirely depend your application.

You can always load all the data you need inside the transaction where the object is first loaded (Hibernate.initialise, or sometimes just calling the getter will work), this will remove your exception: the down side to this is to will find that you are regularly leading a lot of data and could have performance issues

Another way is to pass the Id to where you need to use the object, load a new one from the database and do your work inside the transaction, passing ids a lot is not very OO but sometimes it's the best option.

If for instance you are having this error in UI bindings or other places where you only want to "get", you may want to consider a "session in view" which will provide a db session for your lazy loading.

I can not tell you what is the best option without knowing about your application and it's architecture.

If you wish to discuss a any of this further please let me know.

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