Results 1 to 14 of 14
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default lazy fetch error, how come?

    I am experimenting with getting stuff from the DB by queries, here is the genetic method I put together, which provides my with some object list that I am asking for at the order dao:

    Java Code:
    Map<String, Object> params = new HashMap<String, Object>();
    		params.put("status", state); // look for shopping cart, wish list
    		params.put("userId", userId);
    		orders = getAllByQuery("from Order o where o.state = :status and o.user.id = :userId", params);
    		
    		if (orders.isEmpty()){
    			return null;
    		}
    		
    		return orders.get(0);


    Java Code:
    public  List<T> getAllByQuery(String queryString, Map<String, Object> params) {
        	EntityManager em = null;
        	EntityTransaction txn = null;
        	List<T> t = null;
        	try{
        		em = ConnectionManager.getEntityManager();
        		txn = em.getTransaction();
        		txn.begin();
        		System.out.println("generic dao getAllByQuery query string: " + queryString);
        		Query query = em.createQuery(queryString);
    	    	//em.createNativeQuery(query);
    	    	
    	    	txn.commit();
    	    	Iterator entries = params.entrySet().iterator();
    	    	String key = "";
    	    	Object value = null;
    	    	while (entries.hasNext()) {
    	    	  Entry thisEntry = (Entry) entries.next();
    	    	  key = (String) thisEntry.getKey();
    	    	  value = thisEntry.getValue();
    	    	  query.setParameter(key, value);
    	    	}
    
    	        //query.getSingleResult();
    	        t = query.getResultList();
    	        for (int i=0; i < t.size() ; i++) {
    	        	System.out.println(i + " The query result list: " +  t.get(i));
    	        }
    	        
        	}
        	catch (HibernateException e) {
        		System.out.println("roll back delete: " + e);
        		txn.rollback();
        		//handleException(e);
        	} 
        	finally {
        		em.close();
        		System.out.println("finally is txn delete open: : " + txn.isActive());
        	}
    	return t;
        }
    But when, some latter, I run the next List (as a matter of testing), I get a lazy fetch error: how come?:

    Java Code:
    for (ProductOrder productOrder : card.getProductOrders()) {
    			System.out.println(">>>>>> " + productOrder.getId());
    		}
    SEVERE: Exception occurred during processing request: could not initialize proxy - no Session
    org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initia lize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImp lementation(AbstractLazyInitializer.java:285)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyIn itializer.invoke(JavassistLazyInitializer.java:185 )
    at com.mycomp.shoponline.model.Product_$$_jvstaaf_0.g etProductMedias(Product_$$_jvstaaf_0.java)
    at com.mycomp.shoponline.appservice.impl.ProductOrder AppServiceImpl.getCardMedia(ProductOrderAppService Impl.java:125)
    Last edited by willemjav; 07-09-2015 at 02:09 PM.

  2. #2
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    The interesting thing is, that when I get my order-list in the "Java_way", the error does not occur!

    Java Code:
    public Order getCard(Integer userId, String state) {
    		List<Order> orders = null;
    		Order currentOrder = null;
    		for(Order order: orders = super.getAll()) {
    			if(order.getUser().getId().equals(userId)) {
    				if(order.getState().equals(state)) {
    					 currentOrder = order;
    					 break;
    				}
    			}
    		}
    		/*
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("status", state); // look for shopping cart, wish list
    		params.put("userId", userId);
    		orders = getAllByQuery("from Order o where o.state = :status and o.user.id = :userId", params);
    		if (orders.isEmpty()){
    			return null;
    		}
    		return orders.get(0);
    		*/
    		return currentOrder;
    	}
    Last edited by willemjav; 07-09-2015 at 02:07 PM.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: lazy fetch error, how come?

    That stack trace doesn't refer to getAllByQuery at all, so where is the error coming from?

    Also what does "in the Java_Way" mean?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    Right! The error does not come from getAllByQuery. So where does it comes from?
    When you look at #2, you'll see the "Java-way": the commented-code causes the error,
    the for loop does actually the same thing without causing the error!

  5. #5
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: lazy fetch error, how come?

    The stacktrace clearly points to a very specific piece of code:

    Java Code:
    com.mycomp.shoponline.appservice.impl.ProductOrder AppServiceImpl.getCardMedia(ProductOrderAppServiceImpl.java:125)
    So what is on line 125 of ProductOrderAppServiceImpl.java? I am going to guess that there is some kind of product entity being used, that product entity has a oneToMany mapping in the form of a property called 'productMedias' and this productMedias collection is not initialized before the transaction is finished.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    Java Code:
    public void CreateCardEntry(ProductOrderModel model) {
    			//System.out.println("order id: " + model.getId() + " model.getProductId() " + model.getProductId() + " model.getProductQuantity() " + model.getProductQuantity());
    			if (model.getProductId() != null && model.getProductQuantity() != null) {
    				getCard(model); // set the wish/ card in case it does not exist
    				ProductOrder currentProductOrder = null;
    				Integer productId = model.getProductId();
    				Order card = productOrderAppService.getCard(getUserId(), "card");
    				Order wishCard = productOrderAppService.getCard(getUserId(), "wish");
    
    etc….

    calls:

    Java Code:
    @Override
    	public void getCard(ProductOrderModel model) {
    		Integer id = getUserId() ;
    		Order entity = productOrderAppService.getCard(id,  model.getState());
    		Order card = productOrderAppService.getCard(id, "card");
    		Order wish = productOrderAppService.getCard(id, "wish");
    		BeanUtils.copyProperties(entity, model);
    		model.setList(card.getProductOrders());
    		model.setShoppingCardMedias(this.productOrderAppService.getCardMedia(entity));
    		model.setWishCardMedias(this.productOrderAppService.getCardMedia(wish));
    		model.setWishCardList(( this.productOrderAppService).getWishList(wish));
    		BeanUtils.copyProperties(model, entity);
    	}


    on its turn:

    Java Code:
    public List<ProductMedia> getCardMedia(Order order)  {
    		List <ProductMedia> medias = new ArrayList();
    		ProductMedia media = null;
    		List <ProductOrder> products = order.getProductOrders();
    		if (products != null) {
    			for (ProductOrder product: products) {
    				List<ProductMedia> productMedias = product.getProduct().getProductMedias(); [COLOR="#FF0000"]line 125!!!![/COLOR]
    				if (productMedias.size() > 0){
    					if (productMedias.size() > 1) {
    							media = productMedias.get(1);
    					}
    					else {
    						media = productMedias.get(0);
    					}
    					medias.add(media);
    				}
    			}
    		}
    		return medias;
    	}
    Last edited by willemjav; 07-09-2015 at 06:14 PM.

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: lazy fetch error, how come?

    Wow, and all that code is on line 125?

    I do spot this in that random code dump:

    Java Code:
    BeanUtils.copyProperties(entity, model);
    That smells like a piece of code which might touch all the properties of an entity and causing all kinds of lazy init problems.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  8. #8
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    No I had to look it up again here it is now see #6
    Last edited by willemjav; 07-09-2015 at 06:19 PM.

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    Let me re- edit post #6 to show you you'r right, just a moment
    Last edited by willemjav; 07-09-2015 at 06:19 PM.

  10. #10
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    Here you are #6

  11. #11
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    I have the getCard(), three times with the exact same name at the dao, app. service and Adapter. So technically an "override"?
    Might that be the problem?

    I could rename them like getCardDao(), getCardAppService() and getCardAdapter()?

    I did that and it did NOT help.

    What is actually going on.
    -ProductOrder (the shopping/ wish card) is a many to many table of Product and Order with an extra column, concerning the product quantity (on the cart)
    -and Product has a one to many with the Table ProductMedia (which has the images etc.)

    The question is where is the lazy-problem taking place:
    1) when getting a productorder member
    (2) when getting a product)
    3) or when getting a product media (of the product of the product-order)

    right here I am lost.....
    Last edited by willemjav; 07-09-2015 at 10:25 PM.

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: lazy fetch error, how come?

    Gimbal has already said what the problem is.
    You have selected an Order in a session (that is, a Hibernate session, not a web session). You have then left that session.
    You then go off and start to burrow into the Order. However the way Hibernate works you can only usually get a single layer in before Hibernate needs to go off and get the rest of it from the database, which requires a session.

    It has nothing to do with the names of your methods.

    For something like getCardMedia I would query the database. You really shouldn't be getting a load of data from the db then trawling through it for the bits you want.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,139
    Rep Power
    13

    Default Re: lazy fetch error, how come?

    I understand
    I before use to run the whole table in a for-get-all-loop and fetch the element/ list with a if-statement.
    That works but you are right tolls, it is a bad habit.
    So when using the get(all)by query I improve that habit significantly!
    But there is another problem coming out of it!
    Since those loops 'automatically' initialise the lazy-tables the get-by-query-way does NOT:
    and here is my problem.....

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: lazy fetch error, how come?

    Except you aren't.
    Your getCardMedia is looping over stuff buried in the Order.
    That should be a query to retrieve the data you need.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. lazy loading
    By sid123 in forum Hibernate
    Replies: 2
    Last Post: 05-02-2013, 03:41 PM
  2. Lazy Initialization
    By onegcr in forum New To Java
    Replies: 1
    Last Post: 08-14-2007, 03:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •