@Override public final void initialize() throws HibernateException { if ( !initialized ) { if ( allowLoadOutsideTransaction ) { permissiveInitialization(); } else if ( session == null ) { throw new LazyInitializationException( "could not initialize proxy - no Session" ); } else if ( !session.isOpen() ) { throw new LazyInitializationException( "could not initialize proxy - the owning Session was closed" ); } else if ( !session.isConnected() ) { throw new LazyInitializationException( "could not initialize proxy - the owning Session is disconnected" ); } else { target = session.immediateLoad( entityName, id ); initialized = true; checkTargetState(); } } else { checkTargetState(); } }
@Test(expected = LazyInitializationException.class) public void selectFromWithoutJoinFetch() { log.info("... selectFromWithoutJoinFetch ..."); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Author a = em.createQuery("SELECT a FROM Author a WHERE id = 1", Author.class).getSingleResult(); log.info("Commit transaction and close Session"); em.getTransaction().commit(); em.close(); try { log.info(a.getFirstName()+" "+a.getLastName()+" wrote "+a.getBooks().size()+" books."); } catch (Exception e) { log.error(e); throw e; } }
public final void initialize() throws HibernateException { if (!initialized) { if ( session==null ) { throw new LazyInitializationException("could not initialize proxy - no Session"); } else if ( !session.isOpen() ) { throw new LazyInitializationException("could not initialize proxy - the owning Session was closed"); } else if ( !session.isConnected() ) { throw new LazyInitializationException("could not initialize proxy - the owning Session is disconnected"); } else { target = session.immediateLoad(entityName, id); initialized = true; checkTargetState(); } } else { checkTargetState(); } }
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel lbText = (JLabel) super.getTableCellRendererComponent(table, null, isSelected, hasFocus, row, column); if (value == null || value instanceof String) { return lbText; } try { lbText.setText(value.toString()); } catch (LazyInitializationException lie) { MainFrame mainFrame = (MainFrame) table .getClientProperty(ClientPropertyName.MAIN_FRAME.toString()); BookModel model = mainFrame.getBookModel(); Session session = model.beginTransaction(); session.refresh((Chapter) value); lbText.setText(value.toString()); model.commit(); } catch (Exception e) { e.printStackTrace(); } return lbText; }
private void refire() { EntityManager em = getEntityManager(); try { for (AlertDefinition def : getAlertDefs(em)) { try { checkRefire(def); } catch (LazyInitializationException e) { // failed to lazily initialize a collection of role: org.rhq.core.domain.alert.AlertDefinition.alerts, could not initialize proxy - no Session log.debug("spurious exception?", e); def = em.find(AlertDefinition.class, def.getId()); checkRefire(def); } } } finally { em.close(); } }
/** * Interception of access to the named field * * @param target The call target * @param fieldName The name of the field. * @param value The value. * * @return ? */ protected final Object intercept(Object target, String fieldName, Object value) { if ( initializing ) { return value; } if ( uninitializedFields != null && uninitializedFields.contains( fieldName ) ) { if ( session == null ) { throw new LazyInitializationException( "entity with lazy properties is not associated with a session" ); } else if ( !session.isOpen() || !session.isConnected() ) { throw new LazyInitializationException( "session is not connected" ); } final Object result; initializing = true; try { result = ( (LazyPropertyInitializer) session.getFactory().getEntityPersister( entityName ) ) .initializeLazyProperty( fieldName, target, session ); } finally { initializing = false; } // let's assume that there is only one lazy fetch group, for now! uninitializedFields = null; return result; } else { return value; } }
private void throwLazyInitializationException(String message) { throw new LazyInitializationException( "failed to lazily initialize a collection" + (role == null ? "" : " of role: " + role) + ", " + message ); }
/** * <strong>使用广度优先搜索收集</strong>当前实体及其所有子孙实体到集合,叶子实体排在最前面<br/> * 这样才能保证先删除子孙节点,后删除父节点,避免违反外键约束 * @param currentEntity 存放当前实体及其所有子孙实体的集合 * @param treeEntities 所有实体的集合 * @return 当前实体及其所有子孙实体的集合,叶子实体排在集合最前面 */ @SuppressWarnings("unchecked") @Transactional private LinkedList<SelfReference<T>> bfsTraverse(SelfReference<T> currentEntity, LinkedList<SelfReference<T>> treeEntities) { // 无法获取子孙类目时,在事务中重新获取当前节点 try { currentEntity.getChildren().size(); } catch (LazyInitializationException e) { ID id = (ID) ((BaseEntity)currentEntity).getId(); currentEntity = (SelfReference<T>) findOne(id); } // 队列,用于广度优先遍历。每一时刻,队列所包含的节点是那些本身已经被访问,而它的邻居(这里即子节点)还有未被访问的节点 Queue<SelfReference<T>> queue = new ArrayDeque<>(); treeEntities.addFirst(currentEntity); // 对当前遍历到的元素执行的操作:加在头部,后续用于删除节点(避免违反外键约束) queue.add(currentEntity); // 加在尾部 while (queue.size() != 0) { // 直到队列为空 SelfReference<T> parent = queue.remove(); // 移除在队列头部的节点 if(parent.getChildren().size() != 0) { parent.getChildren().forEach(child -> { treeEntities.addFirst((SelfReference<T>) child); // 对当前遍历到的元素执行的操作:加在头部 queue.add((SelfReference<T>) child); // 加在尾部 }); } } return treeEntities; }
public Department getDepartment() { Department dept = null; try { dept = this.getSubjectArea().getDepartment(); if(dept.toString()==null) { } } catch (LazyInitializationException lie) { new _RootDAO().getSession().refresh(this); dept = this.getSubjectArea().getDepartment(); } return (dept); }
public Set<Location> getRooms() { try { return super.getRooms(); } catch (LazyInitializationException e) { (new AssignmentDAO()).getSession().merge(this); return super.getRooms(); } }
@Deprecated public String getHtmlHint(String preference) { try { if (!Hibernate.isPropertyInitialized(this, "roomType") || !Hibernate.isInitialized(getRoomType())) { return LocationDAO.getInstance().get(getUniqueId()).getHtmlHintImpl(preference); } else { return getHtmlHintImpl(preference); } } catch (LazyInitializationException e) { return LocationDAO.getInstance().get(getUniqueId()).getHtmlHintImpl(preference); } }
@Test(expected = LazyInitializationException.class) public void testFailLazyAccess() { User user = entityManager.find(User.class, 1L); assertNotNull(user); // Lazy init exception cars is mapped as lazy user.getCars().stream().forEach(System.out::println); }
@Test(expected = LazyInitializationException.class) public void testFailLazyAccessByExplicitJoinInJPAQL() { TypedQuery<User> loadUserQuery = entityManager.createQuery( "select usr from User usr left outer join usr.cars cars where cars.licensePlate = :licensePlate", User.class); loadUserQuery.setParameter("licensePlate", "HIBERNATE"); User user = loadUserQuery.getSingleResult(); user.getCars().stream().forEach(System.out::println); }
@Test public void testGetUserLazyProperties() { List<User> users = service.getAllUsers4LazyTest(); assertNotNull(users); assertThat(users.size(), greaterThan(0)); User user = users.get(0); assertThat(user, notNullValue()); assertThat(user.getName(), notNullValue()); try { user.getType().getValue(); } catch (Exception e) { assertThat(e, instanceOf(LazyInitializationException.class)); } }
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if ( constructed ) { Object result = invoke( method, args, proxy ); if ( result == INVOKE_IMPLEMENTATION ) { Object target = getImplementation(); try { final Object returnValue; if ( ReflectHelper.isPublic( persistentClass, method ) ) { if ( ! method.getDeclaringClass().isInstance( target ) ) { throw new ClassCastException( target.getClass().getName() ); } returnValue = method.invoke( target, args ); } else { if ( !method.isAccessible() ) { method.setAccessible( true ); } returnValue = method.invoke( target, args ); } return returnValue == target ? proxy : returnValue; } catch ( InvocationTargetException ite ) { throw ite.getTargetException(); } } else { return result; } } else { // while constructor is running if ( method.getName().equals( "getHibernateLazyInitializer" ) ) { return this; } else { throw new LazyInitializationException( "unexpected case hit, method=" + method.getName() ); } } }
protected final Object intercept(Object target, String fieldName, Object value) { if ( initializing ) { return value; } if ( uninitializedFields != null && uninitializedFields.contains( fieldName ) ) { if ( session == null ) { throw new LazyInitializationException( "entity with lazy properties is not associated with a session" ); } else if ( !session.isOpen() || !session.isConnected() ) { throw new LazyInitializationException( "session is not connected" ); } final Object result; initializing = true; try { result = ( ( LazyPropertyInitializer ) session.getFactory() .getEntityPersister( entityName ) ) .initializeLazyProperty( fieldName, target, session ); } finally { initializing = false; } uninitializedFields = null; //let's assume that there is only one lazy fetch group, for now! return result; } else { return value; } }
/** * Initialize the collection, if possible, wrapping any exceptions * in a runtime exception * @param writing currently obsolete * @throws LazyInitializationException if we cannot initialize */ protected final void initialize(boolean writing) { if (!initialized) { if (initializing) { throw new LazyInitializationException("illegal access to loading collection"); } throwLazyInitializationExceptionIfNotConnected(); session.initializeCollection(this, writing); } }
private void throwLazyInitializationException(String message) { throw new LazyInitializationException( "failed to lazily initialize a collection" + ( role==null ? "" : " of role: " + role ) + ", " + message ); }
@Test(expected = LazyInitializationException.class) public void lazyLoadingOutOfTransactionFailsWithException() { startTransaction(); Employee e = entityManager.find(Employee.class, employeeId); commitTransaction(); e.getProjects().size(); // this causes an exception, as Tx had ended }
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel lbText = (JLabel) super.getTableCellRendererComponent(table, null, isSelected, hasFocus, row, column); if (value instanceof String) { return lbText; } else { @SuppressWarnings("unchecked") List<Location> list = (List<Location>) value; try { lbText.setText(StringUtils.join(list, ", ")); } catch (LazyInitializationException lie) { MainFrame mainFrame = (MainFrame) table .getClientProperty(ClientPropertyName.MAIN_FRAME .toString()); BookModel model = mainFrame.getBookModel(); Session session = model.beginTransaction(); for (Location location : list) { session.refresh(location); } lbText.setText(StringUtils.join(list, ", ")); model.commit(); } catch (Exception e) { e.printStackTrace(); } } return lbText; }
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel lbText = (JLabel) super.getTableCellRendererComponent(table, null, isSelected, hasFocus, row, column); lbText.setBorder(SwingUtil.getBorder(Color.white, 2)); StrandLabel lbStrand = null; if (value == null || value instanceof String) { return lbText; } try { lbStrand = new StrandLabel((Strand) value); } catch (LazyInitializationException lie) { MainFrame mainFrame = (MainFrame) table .getClientProperty(ClientPropertyName.MAIN_FRAME.toString()); BookModel model = mainFrame.getBookModel(); Session session = model.beginTransaction(); session.refresh((Strand) value); lbStrand = new StrandLabel((Strand) value); model.commit(); } catch (Exception e) { e.printStackTrace(); } if (lbStrand != null) { lbStrand.setBackground(lbText.getBackground()); lbStrand.setOpaque(true); return lbStrand; } return lbText; }
@Test public void sameLoadedState() throws PersistenceException { // Store a User Message UserMessageEntity userMsg = updManager.storeMessageUnit(new org.holodeckb2b.common.messagemodel.UserMessage(TestData.userMsg1)); assertTrue(userMsg.isLoadedCompletely()); // Update it and check it is still loaded completely updManager.setProcessingState(userMsg, userMsg.getCurrentProcessingState().getState(), T_NEW_PROC_STATE_1); assertEquals(T_NEW_PROC_STATE_1, userMsg.getCurrentProcessingState().getState()); assertTrue(userMsg.isLoadedCompletely()); assertFalse(Utils.isNullOrEmpty(userMsg.getPayloads())); // Also check that when the indicator is not set previously the object does not load on update em.getTransaction().begin(); ErrorMessage errorMsgJPA = new ErrorMessage(TestData.error4); em.persist(errorMsgJPA); em.getTransaction().commit(); ErrorMessageEntity errorMsg = new ErrorMessageEntity(em.find(ErrorMessage.class, errorMsgJPA.getOID())); assertFalse(errorMsg.isLoadedCompletely()); // Update it and check it is still not loaded completely updManager.setProcessingState(errorMsg, errorMsg.getCurrentProcessingState().getState(), T_NEW_PROC_STATE_2); assertEquals(T_NEW_PROC_STATE_2, errorMsg.getCurrentProcessingState().getState()); assertFalse(errorMsg.isLoadedCompletely()); try { Utils.isNullOrEmpty(errorMsg.getErrors()); fail(); } catch (LazyInitializationException notLoaded) { // This is expected! } }
@Test(expected=LazyInitializationException.class) public void findOne_Uninitialized() { // given Judgment ccJudgment = testPersistenceObjectFactory.createCcJudgment(); // execute Judgment dbJudgment = judgmentRepository.findOne(ccJudgment.getId()); // assert assertNotNull(dbJudgment); dbJudgment.getJudges().size(); }
/** * Tests that reloadEntity() will eager fetch any specified relationships, * even if the entity is already managed by the current Hibernate session in * which reloadEntity() is called. */ public void testReloadOfManagedEntityEagerFetchesRequestedRelationships() { genericEntityDao.doInTransaction(new DAOTransaction() { public void runTransaction() { Screen screen = MakeDummyEntities.makeDummyScreen(1); screen.createLibraryScreening(_adminUser, screen.getLeadScreener(), new LocalDate()); genericEntityDao.persistEntity(screen); } }); class Txn implements DAOTransaction { //Screen screen; LabActivity activity; public void runTransaction() { //screen = genericEntityDao.findEntityByProperty(Screen.class, Screen.facilityId.getPropertyName(), "1"); //screen = genericEntityDao.reloadEntity(screen, true, "leadScreener"); activity = genericEntityDao.findEntityByProperty(LabActivity.class, "dateOfActivity", new LocalDate()); activity = genericEntityDao.reloadEntity(activity, true, Activity.performedBy.castToSubtype(LabActivity.class)); } }; Txn txn = new Txn(); genericEntityDao.doInTransaction(txn); //txn.screen.getLeadScreener().getFullNameLastFirst(); // no LazyInitExc txn.activity.getPerformedBy().getFullNameLastFirst(); // no LazyInitExc try { //txn.screen.getLabHead().getFullNameLastFirst(); txn.activity.getScreen().getTitle(); fail("expected LazyInitializationException on screen.getLabHead()"); } catch (LazyInitializationException e) {} }
/** * For JAXB only. * * @return this.getDescriptionElement() */ @XmlElement(name = "description-element") @XmlJavaTypeAdapter(value = ElementXmlAdapter.class) @SuppressWarnings("unused") @Deprecated private Element getPostElementJAXB() { try { return getPostElement(); } catch (LazyInitializationException e) { LOGGER.trace("ignored: {}", e.getLocalizedMessage()); return null; } }
@Test(expected = LazyInitializationException.class) public void filesContentIsFetchedLazily() throws Exception { storage.save(fileWithContentAndXmlSchema("test-content".getBytes()), userId); Session currentSession = sessionFactory.getCurrentSession(); currentSession.clear(); UserFile theOnlyFile = getFirstUploadedFileAndAssertThatItIsTheOnlyOneAvailableFor(userId); currentSession.evict(theOnlyFile); theOnlyFile.getContent();// content must be not initialized }
@Test(expected = LazyInitializationException.class) public void allFilesQueryDoesNotReturnFileContent() throws Exception { addOneFile("fileName1"); Session currentSession = sessionFactory.getCurrentSession(); currentSession.clear(); Collection<ProjectFile> projectFiles = projectFileStorage.findAllFilesFor(projectEntry); assertThat(projectFiles.size(), equalTo(1)); ProjectFile file = projectFiles.iterator().next(); currentSession.evict(file); file.getFileContent(); }
@Test public void testGetByIdLazyInitializeException() { QuestionnaireForm actualQuestionnaireForm = baseJpaDao.getById(53500l); Assert.assertNotNull(actualQuestionnaireForm); Assert.assertNotNull(actualQuestionnaireForm.getId()); try { actualQuestionnaireForm.getQuestions().get(0); Assert.fail("Questions should be lazily initialized"); } catch (LazyInitializationException e) { Assert.assertNotNull(actualQuestionnaireForm.getQuestions()); } }
@Transient public String getPrecioString() { try { BigDecimal precio = getPrecio(); NumberFormat nb = NumberFormat.getCurrencyInstance(); nb.setMinimumFractionDigits(2); nb.setMaximumFractionDigits(2); return nb.format(precio.doubleValue()); } catch(LazyInitializationException lie) { return "Paquete no activo"; } }