Hibernate, Java: session or session closed

I already saw this problem in Stackoverflow, but nothing helped me solve my problem.

I am new to Hibernate and have a project that needs to be done in Java and MySQL, and thus use hibernate. I managed to reach my data to change it, to delete it, but I am blocking the method because I have one exception that comes up. And it is clear that I understand that there are still not all the threads that I can remove this error:

Here is my mistake:

org.hibernate.LazyInitializationException Grave: failed to lazily initialize role collection: DAO.User.files, session or session is not closed org.hibernate.LazyInitialization Exception: failed to lazily initialize role collection: DAO.User.files, session or session is not closed in org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException (AbstractPersistentCollection.java{5858) in org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIolent.ollection.olent.ollection.ollection.ollection.nlection.nlection.nolction.ollection.ollection.nolction.ollection.nolction.ollection.ollection.ollection.nolction.nlocation at org.hibernate.collection.PersistentSet.add (PersistentSet.java:189) in DAO.UserDAO.removeGroupAddUserFiles (UserDAO.java:252) in javaapplication5.JavaApplication5.main (JavaApplication5.java:37)

And here are my Java classes:

public static void main(String[] args) { GroupDAO grDAO = new GroupDAO(); List[] lists = grDAO.removeGroup(grDAO.getGroupById(1)); FileDAO fiDAO = new FileDAO(); fiDAO.removeGroupAddFiles(lists); UserDAO usDAO = new UserDAO(); usDAO.removeGroupAddUserFiles(lists); } 

GroupDAO.java:

 public List[] removeGroup(Group group) { Set<File> setFiles = group.getFiles(); Set<User> setUsers = group.getUsers_1(); List[] lists = new List[2]; Iterator<File> itFiles = setFiles.iterator(); Iterator<User> itUsers = setUsers.iterator(); List<File> listFiles = new ArrayList<File>(); List<User> listUsers = new ArrayList<User>(); while (itFiles.hasNext()) { listFiles.add(itFiles.next()); } while (itUsers.hasNext()) { listUsers.add(itUsers.next()); } lists[0] = listUsers; lists[1] = listFiles; org.hibernate.Transaction tx = session.beginTransaction(); session.delete(group); tx.commit(); return lists; } 

FileDAO.java:

 public List[] removeGroupAddFiles(List[] lists) { System.out.println("5 : " + session.isOpen()); System.out.println("6 : " + session.isOpen()); Iterator<File> itFile = lists[1].iterator(); System.out.println("7 : " + session.isOpen()); org.hibernate.Transaction tx = session.beginTransaction(); while (itFile.hasNext()) { System.out.println("8 : " + session.isOpen()); Iterator<User> itUser = lists[0].iterator(); System.out.println("9 : " + session.isOpen()); File f = itFile.next(); while (itUser.hasNext()) { System.out.println("10 : " + session.isOpen()); System.out.println("11 : " + session.isOpen()); User u = itUser.next(); System.out.println("12 : " + session.isOpen()); File fCopie = new File(u, f.getName() + "_" + u.getFirstName() + "_" + u.getLastName(), f.getExtension(), f.getSize(), f.getCreatedAt(), f.getUpdateAt()); System.out.println("13 : " + session.isOpen()); session.save(fCopie); System.out.println("14 : " + session.isOpen()); } } tx.commit(); return lists; } 

UserDAO.java:

 public List[] removeGroupAddUserFiles(List[] lists) { System.out.println("15 : " + session.isOpen()); Iterator<User> itUser = lists[0].iterator(); System.out.println("16 : " + session.isOpen()); org.hibernate.Transaction tx = session.beginTransaction(); while (itUser.hasNext()) { System.out.println("17 : " + session.isOpen()); Iterator<File> itFile = lists[1].iterator(); System.out.println("18 : " + session.isOpen()); User u = itUser.next(); while (itFile.hasNext()) { System.out.println("19 : " + session.isOpen()); File f = itFile.next(); System.out.println("20 : " + session.isOpen()); try { u.getFiles().add(f); } catch (LazyInitializationException e) { e.printStackTrace(); } System.out.println("21 : " + session.isOpen()); } try { session.update(u); } catch (ConstraintViolationException e) { e.printStackTrace(); } System.out.println("22 : " + session.isOpen()); } tx.commit(); return lists; } 

My code is superfluous, I know him (him), he should try to avoid the problem of a closed session.

The session closes at the line:

U.getFiles (). Add (f);

And HibernateUtil.java:

 public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // load from different directory SessionFactory sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory(); return sessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } } 

I put the display of session.isOpen () everywhere in my code, as well as trying to deal with the error. Thus, the program continues and shows me systematically true, whether before or after the exception!

+8
source share
3 answers

Common problem: you open a transaction, create a Hibernate object with FetchType LAZY . Hibernate creates a proxy for the collection, which will load objects the first time collections are used. You are closing a transaction and trying to access this collection. The hibernation failed because the transaction was closed, so you received an error message.

You must reconfigure your code to never return an object with unified proxies from a transaction block. You must either load collections, or an evict object from the session, or not collect the collection automatically (remove them from POJO).

+13
source

If you store your hibernate proxy objects directly in your application, they will be available until the session is active. after the session is closed, you cannot access these objects. if you try to access them after closing the transaction, you will get this

 org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException 

Therefore, it is always better to create a new copy of your proxy objects if you intend to use them after closing the transaction.

+3
source

By making the following line in web.xml, we can fix the LazyInitilization exception.

 <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 

Link: http://blog.gmorales.net/2012/03/how-to-solve-orghibernatelazyinitializa.html ?

-1
source

Source: https://habr.com/ru/post/906749/


All Articles