You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@wicket.apache.org by "Mathias P.W Nilsson" <ma...@snyltarna.se> on 2008/05/04 01:20:10 UTC

How to avoid Lazy loading exception

Is there any good tutorial on wicket, hibernate and spring? When dealing with
my lazy many to one relations I get lazy loading exception. Very annoing.

Lets say I have an Item class that has many to one relations to a category. 
I list the items in a wicket page and when click a link I do
setResponsePage( new ItemPage( item ) );

when getting to this page I get a lazy loading exception on the category.
How's that? I thought that open session in view should allow this. Is there
any way of dealing with this?
-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17040941.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by lars vonk <la...@gmail.com>.
Did you put the filter-mapping of the opensessioninviewfilter before the
wicketfilter? The order of filter-mapping definitions in web.xml is the
order in which the filters are executed.

- Lars

On Sun, May 4, 2008 at 7:01 PM, Mathias P.W Nilsson <ma...@snyltarna.se>
wrote:

>
> I have session in view filter but still gets LazyLoadingException even if
> I
> use detached models! Ahhh...
>
> Solved it temporarily by using Eager fetch but this is going to end up bad
> if everything is eager.
> --
> View this message in context:
> http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17048739.html
> Sent from the Wicket - User mailing list archive at Nabble.com.
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
> For additional commands, e-mail: users-help@wicket.apache.org
>
>

Re: How to avoid Lazy loading exception

Posted by Eelco Hillenius <ee...@gmail.com>.
Fwiw Mathias, here is a model class that I like to use in the project I work
on:

/**

 * LDM for domain objects. Detaches (nulls) object after each request.

 */

public class DomainObjectModel<T extends DomainObject>
extendsLoadableDetachableModel {


  @SpringBean

  private GenericHibernateDao dao;


  private final Class<T> domainClass;


  private final Long id;


  /**

   * Construct with class and id; next invocation will trigger loading the

   * object with the id.

   *

   * @param domainClass

   * @param id

   */

  public DomainObjectModel(Class<T> domainClass, Long id) {

    if (domainClass == null) {

      throw new IllegalArgumentException("domainClass may not be null");

    }

    if (id == null) {

      throw new IllegalArgumentException("id may not be null");

    }

    SpringInjector.injectDependencies(this);

    this.domainClass = domainClass;

    this.id = id;

  }


 /**

  * Construct with domain object instance, which will be reused for the

  * current request.

  *

  * @param domainObject

  */

  @SuppressWarnings("unchecked")

  public DomainObjectModel(T domainObject) {

    super(domainObject);

    if (domainObject == null) {

      throw new IllegalArgumentException("domainObject may not be null");

    }

    SpringInjector.injectDependencies(this);

    this.domainClass = (Class<T>)

    HibernateProxyHelper.getClassWithoutInitializingProxy(domainObject);

    this.id = domainObject.getId();

  }


  @Override

  public boolean equals(Object obj) {

    return Objects.equal(obj, getObject());

  }


  @Override

  public int hashCode() {

    return Objects.hashCode(getObject());

  }


  /**

   * @see org.apache.wicket.model.LoadableDetachableModel#load()

   */

  @Override

  protected Object load() {

    return dao.load(domainClass, id);

  }


  @SuppressWarnings("unchecked")

  @Override

  public T getObject() {

    return (T) super.getObject();

  }

}


Where DomainObject is:


/**

 * Should be implemented by all normal domain objects.

 */

public interface DomainObject extends Serializable {


 /**

  * @return The id of the domain object

  */

  Long getId();

}


Might not be what you want, but it is probably a good idea to make such a
model class that you can reuse throughout your project(s).


Probably also can be improved with Wicket 1.4, but I didn't get to look at
that yet :-)


Eelco


On Sun, May 4, 2008 at 10:11 AM, Igor Vaynberg <ig...@gmail.com>
wrote:

> you still have something misconfigured or you are not using detachable
> models where you should. ive built plenty of hibernate+spring+wicket
> apps to know that it works just fine and is pretty easy to do. if you
> want you can post a quickstart that demonstrates your problem and
> someone might be able to help you.
>
> -igor
>
>
> On Sun, May 4, 2008 at 10:01 AM, Mathias P.W Nilsson
> <ma...@snyltarna.se> wrote:
> >
> >  I have session in view filter but still gets LazyLoadingException even
> if I
> >  use detached models! Ahhh...
> >
> >  Solved it temporarily by using Eager fetch but this is going to end up
> bad
> >  if everything is eager.
> >  --
> >  View this message in context:
> http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17048739.html
> >
> >
> > Sent from the Wicket - User mailing list archive at Nabble.com.
> >
> >
> >  ---------------------------------------------------------------------
> >  To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
> >  For additional commands, e-mail: users-help@wicket.apache.org
> >
> >
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
> For additional commands, e-mail: users-help@wicket.apache.org
>
>

Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
Thanks igor! 

I think I have missunderstood the whole thing about detachable models. I
must re-read this.  

Thanks for your time and effort. 
-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17067785.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by Igor Vaynberg <ig...@gmail.com>.
you are not using a detachable model for your items

List<se.edgesoft.hairless.entities.item.Item> items = new
ArrayList<se.edgesoft.hairless.entities.item.Item>();

you are keeping them in that ^ list across requests, which detaches
them from the session, and then you are passing one of those to the
page.

instead of using listdataprovider you should use a dataprovider in
that uses detachablemodels for each individual item

-igor


On Mon, May 5, 2008 at 9:30 AM, Mathias P.W Nilsson
<ma...@snyltarna.se> wrote:
>
>  Yes, sorry. I have tried removing unessesary code. The dao objects is from
>  the base class that is sping injected via @SpringBean
>
>
>  This is the class that lists the items. When clicking on a link that edits
>  or adds an item see ItemPage
>
>
>  public class ItemListPage extends BaseAdministrationPage{
>
>         private List<ItemFilter> filters = new LinkedList<ItemFilter>();
>         private AggregatedItem aggregatedItem;
>         private WebMarkupContainer itemContainer;
>         List<se.edgesoft.hairless.entities.item.Item> items = new
>  ArrayList<se.edgesoft.hairless.entities.item.Item>();
>
>         public List<ItemFilter> getFilters() {
>                 return filters;
>         }
>
>         public ItemListPage(){
>
>                 IModel categoryModel = new LoadableDetachableModel(){
>
>                         private static final long serialVersionUID = 1L;
>                         protected Object load()
>                         {
>                                 List<Category> categories = new LinkedList<Category>();
>                                 List<MainCategory> mainCategories =
>  getCategoryDao().getMainCategories();
>                                 for( MainCategory main : mainCategories ){
>                                         categories.add( main );
>                                         List<SubCategory> subCategories = getCategoryDao().getSubCategories(
>  main );
>                                         for( SubCategory sub : subCategories ){
>                                                 categories.add( sub );
>                                         }
>                                 }
>
>                                 return categories;
>                         }
>                 };
>                 final DropDownChoice categoryChoice = new DropDownChoice("categories", new
>  Model(), categoryModel, new CategoryChoiceRenderer()){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected java.lang.CharSequence getDefaultChoice(final Object selected){
>                                 return "<option value=\"0\">"+
>  getLocalizer().getString("category.choice.default", ItemListPage.this ) +
>  "</option>";
>                         }
>
>                          protected boolean wantOnSelectionChangedNotifications() {
>                                  return true;
>                  }
>
>                          protected void onSelectionChanged(final Object obj ) {
>                                  if( obj instanceof Category ){
>                                          addFilter( new CategoryFilter( (Category) obj ));
>                                  }else{
>                                         removeFilter( CategoryFilter.class );
>                                  }
>
>                                  refreshItemView();
>                  }
>                 };
>                 categoryChoice.setEscapeModelStrings(false);
>
>                 IModel brandsModel = new LoadableDetachableModel(){
>
>                         private static final long serialVersionUID = 1L;
>                         protected Object load()
>                         {
>                                 return getBrandDao().getBrands();
>                         }
>                 };
>                 final DropDownChoice brandChoice = new DropDownChoice("brands", new
>  Model(), brandsModel,new BrandChoiceRenderer()){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected java.lang.CharSequence getDefaultChoice(final Object selected){
>                                 return "<option value=\"0\">"+
>  getLocalizer().getString("brand.choice.default", ItemListPage.this ) +
>  "</option>";
>                         }
>
>                          protected boolean wantOnSelectionChangedNotifications() {
>                                  return true;
>                  }
>
>                          protected void onSelectionChanged(final Object obj ) {
>                                  if( obj instanceof Brand ){
>                                          addFilter( new BrandFilter( (Brand) obj ));
>                                  }else{
>                                         removeFilter( BrandFilter.class );
>                                  }
>
>                                  refreshItemView();
>                  }
>                 };
>
>
>                 Form itemForm = new Form( "itemForm" );
>                 itemForm.add( brandChoice  );
>                 itemForm.add( categoryChoice  );
>                 add( itemForm );
>
>                 itemContainer = new WebMarkupContainer( "itemContainer" ){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                 public boolean isVisible(){
>
>                                 if( getItems() == null ) return false;
>
>                                 if( getItems().isEmpty() ) return false;
>
>                         return true;
>                 }
>         };
>
>                 add( itemContainer );
>                 refreshItemView();
>
>                  add( new Link( "addItem" ){
>
>                                 private static final long serialVersionUID = 1L;
>
>                                 @Override
>                                 public void onClick() {
>                                         setResponsePage( new ItemPage()  );
>                                 }
>                 });
>         }
>
>         private void updateItems(){
>                 aggregatedItem = getItemDao().getAggregatedItem(getFilters());
>                 items = getItemDao().getItems( getFilters() );
>         }
>
>         public List<se.edgesoft.hairless.entities.item.Item> getItems(){
>                 return items;
>         }
>
>         private void refreshItemView(){
>                 updateItems();
>                 itemContainer.addOrReplace( new ItemFragment( "itemPanel" , "itemView") );
>         }
>
>         private final class ItemFragment extends Fragment
>         {
>                 private static final long serialVersionUID = 0L;
>
>                 public ItemFragment( final String panel, final String id)
>                 {
>                         super(panel, id, ItemListPage.this );
>                         final DataView view = new DataView( "itemDataView",  new
>  ListDataProvider( getItems() ) ) {
>
>                                 private static final long serialVersionUID = 1L;
>
>                                 public void populateItem(final Item item) {
>                                         final se.edgesoft.hairless.entities.item.Item i =
>  (se.edgesoft.hairless.entities.item.Item) item.getModelObject();
>                                                 Link itemLink = new Link( "itemLink" ){
>
>                                                         private static final long serialVersionUID = 1L;
>
>                                                         @Override
>                                                         public void onClick() {
>                                                                 setResponsePage( new ItemPage( i ) );
>
>                                                         }
>
>                                                 };
>                                                 item.add( new Label( "id" , i.getId().toString() ) );
>                                                 itemLink.add( new Label( "identifier" , i.getIdentifier() ) );
>                                                 item.add( itemLink );
>                                                 item.add( new Label( "cachedBalance" , i.getCachedBalance().toString()
>  ) );
>                                                 item.add( new Label( "value" , "" + i.getValue() ) );
>                                                 item.add( new Label( "price" , "" + i.getPrice() ) );
>                                                 item.add( new Label( "memberPrice" , "" + i.getMemberPrice() ) );
>                     }
>                 };
>                 view.setItemsPerPage(10);
>                 add(view);
>                 add(new PagingNavigator("navigator", view));
>
>                 }
>         }
>
>         @SuppressWarnings( "unchecked" )
>         public void removeFilter( Class clazz ){
>                  Iterator<ItemFilter> iter = getFilters().iterator();
>                  while( iter.hasNext() ){
>                          ItemFilter filter = (ItemFilter)iter.next();
>
>                          if( clazz.equals( filter.getClass() )){
>                                  iter.remove();
>                                  break;
>                          }
>                  }
>         }
>
>         public void removeFilter( ItemFilter f ){
>                  Iterator<ItemFilter> iter = getFilters().iterator();
>                  while( iter.hasNext() ){
>                          ItemFilter filter = (ItemFilter)iter.next();
>
>                          if( f.getClass().equals( filter.getClass() )){
>                                  iter.remove();
>                                  break;
>                          }
>                  }
>         }
>
>         public void addFilter( ItemFilter f ){
>                 removeFilter( f );
>                 getFilters().add( f );
>         }
>
>
>         public AggregatedItem getAggregatedItem() {
>                 return aggregatedItem;
>         }
>  }
>
>
>  ItemPage
>
>  public class ItemPage extends BaseAdministrationPage {
>
>         private Form itemForm;
>         private Item item;
>         public ItemPage(){
>                 this( new Item() );
>         }
>
>         public ItemPage( Item item ){
>
>                 this.item = item;
>
>                 IModel categoryDetachedFromCompound;
>
>                 if( item.getId() == null ){
>                         item.setEarliestDeliveryDate( new Date() );
>                         categoryDetachedFromCompound = new Model();
>                 }else{
>                         categoryDetachedFromCompound = new Model( getItem().getSubCategory() );
>                 }
>
>                 final CSSFeedbackPanel panel = new CSSFeedbackPanel( "feedback" );
>                 panel.setOutputMarkupId(true);
>                 add( panel );
>
>                 IModel collectionModel = new LoadableDetachableModel(){
>
>                         private static final long serialVersionUID = 1L;
>
>                         protected Object load(){
>                                 return getCollectionDao().getCollections();
>                         }
>                 };
>
>                 IModel colorStoryModel = new LoadableDetachableModel(){
>
>                         private static final long serialVersionUID = 1L;
>                         protected Object load(){
>                                 if( getItem().getCollection() != null && getItem().getBrand() != null ){
>                                         return getColorStoryDao().getColorStories( getItem().getCollection() ,
>  getItem().getBrand());
>                                 }else{
>                                         return Collections.EMPTY_LIST;
>                                 }
>                         }
>         };
>
>                 IModel brandsModel = new LoadableDetachableModel(){
>
>                         private static final long serialVersionUID = 1L;
>                         protected Object load(){
>                                 return getBrandDao().getBrands();
>                         }
>                 };
>
>                 IModel categoryModel = new LoadableDetachableModel(){
>
>                         private static final long serialVersionUID = 1L;
>                         protected Object load(){
>                                 List<Category> categories = new LinkedList<Category>();
>                                 List<MainCategory> mainCategories =
>  getCategoryDao().getMainCategories();
>                                 for( MainCategory main : mainCategories ){
>                                         categories.add( main );
>                                         List<SubCategory> subCategories = getCategoryDao().getSubCategories(
>  main );
>                                         for( SubCategory sub : subCategories ){
>                                                 categories.add( sub );
>                                         }
>                                 }
>                                 return categories;
>                         }
>                 };
>
>                 final DropDownChoice colorStoryChoice = new DropDownChoice("colorStory",
>  colorStoryModel, new ColorStoryChoiceRenderer()){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected java.lang.CharSequence getDefaultChoice(final Object selected){
>                                 return "<option value=\"\">"+
>  getLocalizer().getString("colorstory.choice.default", ItemPage.this ) +
>  "</option>";
>                         }
>                 };
>                 colorStoryChoice.setNullValid( true );
>                 colorStoryChoice.setOutputMarkupId( true );
>
>                 final DropDownChoice collectionChoice = new DropDownChoice("collection",
>  collectionModel, new CollectionChoiceRenderer()){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected java.lang.CharSequence getDefaultChoice(final Object selected){
>                                 return "<option value=\"\">"+
>  getLocalizer().getString("collection.choice.default", ItemPage.this ) +
>  "</option>";
>                         }
>                 };
>                 collectionChoice.add(new AjaxFormComponentUpdatingBehavior("onchange"){
>
>                         private static final long serialVersionUID = 1L;
>
>                         protected void onUpdate(AjaxRequestTarget target){
>                 if( getItem().getCollection() != null && getItem().getBrand()
>  != null ){
>                          target.addComponent(colorStoryChoice);
>
>                 }
>             }
>         });
>                 collectionChoice.setRequired( true );
>
>                 final DropDownChoice categoryChoice = new DropDownChoice("subCategory",
>  categoryDetachedFromCompound,  categoryModel, new CategoryChoiceRenderer()){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected java.lang.CharSequence getDefaultChoice(final Object selected){
>                                 return "<option value=\"0\">"+
>  getLocalizer().getString("category.choice.default", ItemPage.this ) +
>  "</option>";
>                         }
>                 };
>                 categoryChoice.add(new AjaxFormComponentUpdatingBehavior("onchange"){
>
>                         private static final long serialVersionUID = 1L;
>
>                         protected void onUpdate(AjaxRequestTarget target){
>                                 target.addComponent(panel);
>                                 if( ! ( categoryChoice.getModelObject() instanceof SubCategory ) ){
>                                         info( "Please choose a subcategory" );
>                                 }
>             }
>         });
>                 categoryChoice.setRequired( true );
>                 categoryChoice.setEscapeModelStrings(false);
>
>                 final DropDownChoice brandChoice = new DropDownChoice("brand",
>  brandsModel,new BrandChoiceRenderer()){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected java.lang.CharSequence getDefaultChoice(final Object selected){
>                                 return "<option value=\"0\">"+
>  getLocalizer().getString("brand.choice.default", ItemPage.this ) +
>  "</option>";
>                         }
>
>                 };
>                 brandChoice.add(new AjaxFormComponentUpdatingBehavior("onchange"){
>
>                         private static final long serialVersionUID = 1L;
>
>                         protected void onUpdate(AjaxRequestTarget target){
>                 if( getItem().getCollection() != null && getItem().getBrand()
>  != null ){
>                          target.addComponent(colorStoryChoice);
>                 }
>             }
>         });
>                 brandChoice.setRequired( true );
>
>                 TextField identifier = new TextField( "identifier" );
>                 identifier.add( StringValidator.lengthBetween( 1, 255));
>                 identifier.setRequired( true );
>
>                 TextField earliestDeliveryDate = new TextField( "earliestDeliveryDate" );
>                 earliestDeliveryDate.setRequired( true );
>
>                 TextField discount = new TextField( "discount" );
>                 discount.setRequired( true );
>                 discount.add( NumberValidator.range( 0 , 100 ));
>
>                 TextField memberPrice = new TextField( "memberPrice" );
>                 memberPrice.setRequired( true );
>
>                 TextField price = new TextField( "price" );
>                 price.setRequired( true );
>
>                 TextField value = new TextField( "value" );
>                 value.setRequired( true );
>
>                 CompoundPropertyModel itemModel = new CompoundPropertyModel( item );
>
>                 itemForm = new Form( "itemForm", itemModel){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected void onSubmit()
>                 {
>
>
>                                 Item item = (Item) itemForm.getModelObject();
>
>                                 if( ! ( categoryChoice.getModelObject() instanceof SubCategory ) ){
>                                         info( "Please choose a subcategory" );
>                                         return;
>                                 }
>
>                                 item.setSubCategory( (SubCategory) categoryChoice.getModelObject() );
>
>                                 if( ! item.hasGender() ){
>                                         info( "You must choose at least one gender" );
>                                         return;
>                                 }
>
>                                 if( item.getId() == null ){
>                                         item.setAddedDate( new Date() );
>                                         item.setCachedBalance( new Long(0));
>                                 }
>                                 getItemDao().save( item );
>                                 info( "Item saved!" );
>                                 getPage().addOrReplace( new ItemFragment("itemSelectionPanel",
>  "itemFragment"));
>                 }
>                 };
>
>                 itemForm.add( colorStoryChoice  );
>                 itemForm.add( collectionChoice );
>                 itemForm.add( brandChoice );
>                 itemForm.add( categoryChoice );
>                 itemForm.add( memberPrice );
>                 itemForm.add( price );
>                 itemForm.add( value );
>
>                 itemForm.add( new CheckBox( "female" ) );
>                 itemForm.add( new CheckBox( "male" ) );
>                 itemForm.add( new CheckBox( "junior" ) );
>                 itemForm.add( identifier );
>                 itemForm.add( earliestDeliveryDate );
>                 itemForm.add( discount );
>                 add( itemForm );
>
>                 if( getItem().getId() != null  ){
>                         add( new ItemFragment("itemSelectionPanel", "itemFragment"));
>                 }else{
>                         add( new Label("itemSelectionPanel"));
>                 }
>         }
>
>         public Item getItem() {
>                 return item;
>         }
>
>         /**
>          * Fragment for adding , editing  translation for a
>          * store.
>          * The item must exists before this fragment is visible.
>          * @author Mathias Nilsson
>          *
>          */
>         private final class ItemFragment extends Fragment
>
>         {
>                 private static final long serialVersionUID = 1L;
>                 public ItemFragment( String panel, String id ){
>                         super(panel, id, ItemPage.this );
>
>                         IModel availableStoresModel = new LoadableDetachableModel(){
>
>                                 private static final long serialVersionUID = 1L;
>                                 protected Object load()
>                                 {
>                                         return getStoreDao().getAvailableStores( getItem() );
>                                 }
>                         };
>
>                         IModel unusedStoresModel = new LoadableDetachableModel(){
>
>                                 private static final long serialVersionUID = 1L;
>                                 protected Object load()
>                                 {
>                                         return getStoreDao().getUnusedStores( getItem() );
>                                 }
>                         };
>                         final DropDownChoice availableStoresChoice = new DropDownChoice(
>  "availableStores", new Model( "" ),availableStoresModel, new
>  StoreChoiceRenderer()){
>
>                                 private static final long serialVersionUID = 1L;
>
>                                 @Override
>                                 protected java.lang.CharSequence getDefaultChoice(final Object
>  selected){
>                                         return "<option value=\"\">--- Edit item for store ---</option>";
>                                 }
>                                  protected boolean wantOnSelectionChangedNotifications() {
>
>                                          return true;
>                          }
>
>                                  protected void onSelectionChanged(final Object obj ) {
>                                          if( obj instanceof Store ){
>                                                  Store store = (Store) obj;
>                                                 setResponsePage(  new ItemStorePage( getItem(), store ) );
>                                          }
>                          }
>
>                                  @Override
>                                  public boolean isVisible(){
>                                          if( getChoices().size() > 0 ){
>                                                  return true;
>                                          }
>                                          return false;
>                                  }
>                         };
>                         final DropDownChoice unusedStoresChoice = new DropDownChoice(
>  "unusedStores", new Model( "" ),unusedStoresModel, new
>  StoreChoiceRenderer()){
>
>                                 private static final long serialVersionUID = 1L;
>
>                                 @Override
>                                 protected java.lang.CharSequence getDefaultChoice(final Object
>  selected){
>                                         return "<option value=\"\">--- New item for store ---</option>";
>                                 }
>                                  protected boolean wantOnSelectionChangedNotifications() {
>
>                                          return true;
>                          }
>
>                                  protected void onSelectionChanged(final Object obj ) {
>                                          if( obj instanceof Store ){
>                                                  Store store = (Store) obj;
>                                                  setResponsePage(  new ItemStorePage( getItem(), store ) );
>                                          }
>                          }
>
>                                  @Override
>                                  public boolean isVisible(){
>                                          if( getChoices().size() > 0 ){
>                                                  return true;
>                                          }
>                                          return false;
>                                  }
>
>                         };
>
>
>                         final IModel elementModel = new LoadableDetachableModel(){
>
>                                 private static final long serialVersionUID = 1L;
>                                 protected Object load()
>                                 {
>                                         return getCategoryDao().getElements( getItem().getSubCategory() );
>                                 }
>                         };
>
>
>                         Form itemStoreForm = new Form( "itemStoreForm" );
>                         itemStoreForm.add( availableStoresChoice );
>                         itemStoreForm.add( unusedStoresChoice );
>
>                         Link attributeLink = new Link( "attributeLink" ){
>
>                                 @Override
>                                 public void onClick() {
>                                         setResponsePage( new AttributePage( getItem() ) );
>                                 }
>
>                                 @Override
>                                 public boolean isVisible(){
>                                         List<Element> elements = (List<Element> )elementModel.getObject();
>                                         if( elements == null || elements.size() == 0 ){
>                                                 return false;
>                                         }
>
>                                         return true;
>                                 }
>
>                         };
>                         itemStoreForm.add( attributeLink );
>                         add( itemStoreForm );
>
>                 }
>
>         }
>  }
>
>  And when adding translation to the item I get lazy loading exception
>  public class ItemStorePage extends BaseAdministrationPage {
>
>         private Item item;
>         private Store store;
>         private ItemTranslation itemTranslation;
>
>
>         public ItemStorePage( Item item, Store store ){
>                 this.item = item;
>                 this.store = store;
>
>                 initiateTranslation();
>
>
>                 final FeedbackPanel panel = new FeedbackPanel( "feedback" );
>                 panel.setOutputMarkupId(true);
>                 add( panel );
>
>
>
>                 Form itemForm = new Form( "itemForm", new CompoundPropertyModel(
>  getItemTranslation()) ){
>
>                         private static final long serialVersionUID = 1L;
>
>                         @Override
>                         protected void onSubmit()
>                 {
>                                 if( getItemTranslation().getId() == null ){
>                                         /**
>                                          * Add Item to stort
>                                          */
>
>                                         //getItem().addStore( getStore() );
>
>                                         List<Store> stores = new LinkedList<Store>();
>                                         stores.add( getStore() );
>                                         getItem().setStores( stores );
>
>                                         getItemDao().save( getItem() );
>                                 }
>                                 getTranslationDao().save(  getItemTranslation(), getItem() );
>                                 info( "Item updated!" );
>
>                 }
>                 };
>
>                 /** Adding data for translation */
>
>
>
>                 TextArea shortDescription = new TextArea( "shortDescription" );
>                 TextArea longDescription = new TextArea( "longDescription" );
>                 TextField name = new TextField( "name" );
>                 shortDescription.add( StringValidator.lengthBetween( 1, 500 ));
>                 shortDescription.setRequired( true );
>                 longDescription.add( StringValidator.lengthBetween( 1, 1000 ));
>                 longDescription.setRequired( true );
>                 name.add( StringValidator.lengthBetween( 1, 255 ));
>                 name.setRequired( true );
>                 itemForm.add( shortDescription );
>                 itemForm.add( longDescription );
>                 itemForm.add( name );
>                 add( itemForm );
>
>                 add( new Label( "itemId", getItem().getId().toString() ));
>         }
>
>
>
>         public void initiateTranslation(){
>
>
>                 itemTranslation = getTranslationDao().getTranslation( getStore(), getItem(
>  ));
>
>                 if( itemTranslation == null ){
>                         itemTranslation = new ItemTranslation();
>                         itemTranslation.setItem( getItem() );
>                         itemTranslation.setStore( store );
>                 }
>
>         }
>
>         public Item getItem() {
>                 return item;
>         }
>
>         public Store getStore() {
>                 return store;
>         }
>
>         public ItemTranslation getItemTranslation() {
>                 return itemTranslation;
>         }
>  }
>
>
>  --
>  View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17065528.html
>
>
> Sent from the Wicket - User mailing list archive at Nabble.com.
>
>
>  ---------------------------------------------------------------------
>  To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
>  For additional commands, e-mail: users-help@wicket.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
Yes, sorry. I have tried removing unessesary code. The dao objects is from
the base class that is sping injected via @SpringBean


This is the class that lists the items. When clicking on a link that edits
or adds an item see ItemPage


public class ItemListPage extends BaseAdministrationPage{
	
	private List<ItemFilter> filters = new LinkedList<ItemFilter>();
	private AggregatedItem aggregatedItem;
	private WebMarkupContainer itemContainer;
	List<se.edgesoft.hairless.entities.item.Item> items = new
ArrayList<se.edgesoft.hairless.entities.item.Item>();
	
	public List<ItemFilter> getFilters() {
		return filters;
	}

	public ItemListPage(){
	
		IModel categoryModel = new LoadableDetachableModel(){
			private static final long serialVersionUID = 1L;
			protected Object load()
			{
				List<Category> categories = new LinkedList<Category>();
				List<MainCategory> mainCategories =
getCategoryDao().getMainCategories();
				for( MainCategory main : mainCategories ){
					categories.add( main );
					List<SubCategory> subCategories = getCategoryDao().getSubCategories(
main );
					for( SubCategory sub : subCategories ){
						categories.add( sub );
					}
				}
				
				return categories; 
			}
		};
		final DropDownChoice categoryChoice = new DropDownChoice("categories", new
Model(), categoryModel, new CategoryChoiceRenderer()){
			private static final long serialVersionUID = 1L;
			
			@Override
			protected java.lang.CharSequence getDefaultChoice(final Object selected){
				return "<option value=\"0\">"+ 
getLocalizer().getString("category.choice.default", ItemListPage.this ) +
"</option>"; 
			}
			
			 protected boolean wantOnSelectionChangedNotifications() {
				 return true;
	         }
			 
			 protected void onSelectionChanged(final Object obj ) {
				 if( obj instanceof Category ){
					 addFilter( new CategoryFilter( (Category) obj ));
				 }else{
					removeFilter( CategoryFilter.class );
				 }
				 
				 refreshItemView();
	         }
		};
		categoryChoice.setEscapeModelStrings(false);
		
		IModel brandsModel = new LoadableDetachableModel(){
			private static final long serialVersionUID = 1L;
			protected Object load()
			{
				return getBrandDao().getBrands();
			}
		};
		final DropDownChoice brandChoice = new DropDownChoice("brands", new
Model(), brandsModel,new BrandChoiceRenderer()){
			private static final long serialVersionUID = 1L;
			
			@Override
			protected java.lang.CharSequence getDefaultChoice(final Object selected){
				return "<option value=\"0\">"+ 
getLocalizer().getString("brand.choice.default", ItemListPage.this ) +
"</option>"; 
			}
			
			 protected boolean wantOnSelectionChangedNotifications() {
				 return true;
	         }
			 
			 protected void onSelectionChanged(final Object obj ) {
				 if( obj instanceof Brand ){
					 addFilter( new BrandFilter( (Brand) obj ));
				 }else{
					removeFilter( BrandFilter.class );
				 }
				 
				 refreshItemView();
	         }
		};
		
		
		Form itemForm = new Form( "itemForm" );
		itemForm.add( brandChoice  );
		itemForm.add( categoryChoice  );
		add( itemForm );
		
		itemContainer = new WebMarkupContainer( "itemContainer" ){
			private static final long serialVersionUID = 1L;

			@Override
        	public boolean isVisible(){
				
				if( getItems() == null ) return false;
				
				if( getItems().isEmpty() ) return false;
        		
        		return true;
        	}
        };
		
		add( itemContainer );
		refreshItemView();
		
		 add( new Link( "addItem" ){
				private static final long serialVersionUID = 1L;

				@Override
				public void onClick() {
					setResponsePage( new ItemPage()  );
				}
	        });
	}
	
	private void updateItems(){
		aggregatedItem = getItemDao().getAggregatedItem(getFilters());
		items = getItemDao().getItems( getFilters() );
	}
	
	public List<se.edgesoft.hairless.entities.item.Item> getItems(){
		return items;
	}
	
	private void refreshItemView(){
		updateItems();
		itemContainer.addOrReplace( new ItemFragment( "itemPanel" , "itemView") );
	}
	
	private final class ItemFragment extends Fragment
	{
		private static final long serialVersionUID = 0L;

		public ItemFragment( final String panel, final String id)
		{
			super(panel, id, ItemListPage.this );
			final DataView view = new DataView( "itemDataView",  new
ListDataProvider( getItems() ) ) {
				private static final long serialVersionUID = 1L;

				public void populateItem(final Item item) {
					final se.edgesoft.hairless.entities.item.Item i =
(se.edgesoft.hairless.entities.item.Item) item.getModelObject();
						Link itemLink = new Link( "itemLink" ){
							private static final long serialVersionUID = 1L;

							@Override
							public void onClick() {
								setResponsePage( new ItemPage( i ) );
								
							}
							
						};
						item.add( new Label( "id" , i.getId().toString() ) );
						itemLink.add( new Label( "identifier" , i.getIdentifier() ) );
						item.add( itemLink );
						item.add( new Label( "cachedBalance" , i.getCachedBalance().toString()
) );
						item.add( new Label( "value" , "" + i.getValue() ) );
						item.add( new Label( "price" , "" + i.getPrice() ) );
						item.add( new Label( "memberPrice" , "" + i.getMemberPrice() ) );
	            }
	        };
	        view.setItemsPerPage(10);
	        add(view);
	        add(new PagingNavigator("navigator", view));

		}
	}
	
	@SuppressWarnings( "unchecked" )
	public void removeFilter( Class clazz ){
		 Iterator<ItemFilter> iter = getFilters().iterator();
		 while( iter.hasNext() ){
			 ItemFilter filter = (ItemFilter)iter.next();
			 
			 if( clazz.equals( filter.getClass() )){
				 iter.remove();
				 break;
			 }
		 }
	}
	
	public void removeFilter( ItemFilter f ){
		 Iterator<ItemFilter> iter = getFilters().iterator();
		 while( iter.hasNext() ){
			 ItemFilter filter = (ItemFilter)iter.next();
			 
			 if( f.getClass().equals( filter.getClass() )){
				 iter.remove();
				 break;
			 }
		 }
	}
	
	public void addFilter( ItemFilter f ){
		removeFilter( f );
		getFilters().add( f );
	}

	
	public AggregatedItem getAggregatedItem() {
		return aggregatedItem;
	}
}


ItemPage

public class ItemPage extends BaseAdministrationPage {
	
	private Form itemForm;
	private Item item;
	public ItemPage(){
		this( new Item() );
	}
	
	public ItemPage( Item item ){
	
		this.item = item;
		
		IModel categoryDetachedFromCompound;
		
		if( item.getId() == null ){
			item.setEarliestDeliveryDate( new Date() );
			categoryDetachedFromCompound = new Model();
		}else{
			categoryDetachedFromCompound = new Model( getItem().getSubCategory() );
		}

		final CSSFeedbackPanel panel = new CSSFeedbackPanel( "feedback" );
		panel.setOutputMarkupId(true);
		add( panel );
		
		IModel collectionModel = new LoadableDetachableModel(){
			private static final long serialVersionUID = 1L;
			protected Object load(){
				return getCollectionDao().getCollections();
			}
		};
		
		IModel colorStoryModel = new LoadableDetachableModel(){
			private static final long serialVersionUID = 1L;
			protected Object load(){
				if( getItem().getCollection() != null && getItem().getBrand() != null ){
					return getColorStoryDao().getColorStories( getItem().getCollection() ,
getItem().getBrand());
				}else{
					return Collections.EMPTY_LIST;
				}
			}
        };

		IModel brandsModel = new LoadableDetachableModel(){
			private static final long serialVersionUID = 1L;
			protected Object load(){
				return getBrandDao().getBrands();
			}
		};

		IModel categoryModel = new LoadableDetachableModel(){
			private static final long serialVersionUID = 1L;
			protected Object load(){
				List<Category> categories = new LinkedList<Category>();
				List<MainCategory> mainCategories =
getCategoryDao().getMainCategories();
				for( MainCategory main : mainCategories ){
					categories.add( main );
					List<SubCategory> subCategories = getCategoryDao().getSubCategories(
main );
					for( SubCategory sub : subCategories ){
						categories.add( sub );
					}
				}
				return categories; 
			}
		};
		
		final DropDownChoice colorStoryChoice = new DropDownChoice("colorStory", 
colorStoryModel, new ColorStoryChoiceRenderer()){
			private static final long serialVersionUID = 1L;

			@Override
			protected java.lang.CharSequence getDefaultChoice(final Object selected){
				return "<option value=\"\">"+ 
getLocalizer().getString("colorstory.choice.default", ItemPage.this ) +
"</option>"; 
			}
		};
		colorStoryChoice.setNullValid( true );
		colorStoryChoice.setOutputMarkupId( true );
		
		final DropDownChoice collectionChoice = new DropDownChoice("collection", 
collectionModel, new CollectionChoiceRenderer()){
			private static final long serialVersionUID = 1L;

			@Override
			protected java.lang.CharSequence getDefaultChoice(final Object selected){
				return "<option value=\"\">"+ 
getLocalizer().getString("collection.choice.default", ItemPage.this ) +
"</option>"; 
			}
		};
		collectionChoice.add(new AjaxFormComponentUpdatingBehavior("onchange"){
			private static final long serialVersionUID = 1L;

			protected void onUpdate(AjaxRequestTarget target){
            	if( getItem().getCollection() != null && getItem().getBrand()
!= null ){
            		 target.addComponent(colorStoryChoice);
            		
            	}
            }
        });
		collectionChoice.setRequired( true );
		
		final DropDownChoice categoryChoice = new DropDownChoice("subCategory",
categoryDetachedFromCompound,  categoryModel, new CategoryChoiceRenderer()){
			private static final long serialVersionUID = 1L;
			
			@Override
			protected java.lang.CharSequence getDefaultChoice(final Object selected){
				return "<option value=\"0\">"+ 
getLocalizer().getString("category.choice.default", ItemPage.this ) +
"</option>"; 
			}
		};
		categoryChoice.add(new AjaxFormComponentUpdatingBehavior("onchange"){
			private static final long serialVersionUID = 1L;

			protected void onUpdate(AjaxRequestTarget target){
				target.addComponent(panel);
				if( ! ( categoryChoice.getModelObject() instanceof SubCategory ) ){
					info( "Please choose a subcategory" );
				}
            }
        });
		categoryChoice.setRequired( true );
		categoryChoice.setEscapeModelStrings(false);
		
		final DropDownChoice brandChoice = new DropDownChoice("brand",
brandsModel,new BrandChoiceRenderer()){
			private static final long serialVersionUID = 1L;
			
			@Override
			protected java.lang.CharSequence getDefaultChoice(final Object selected){
				return "<option value=\"0\">"+ 
getLocalizer().getString("brand.choice.default", ItemPage.this ) +
"</option>"; 
			}
			
		};
		brandChoice.add(new AjaxFormComponentUpdatingBehavior("onchange"){
			private static final long serialVersionUID = 1L;

			protected void onUpdate(AjaxRequestTarget target){
            	if( getItem().getCollection() != null && getItem().getBrand()
!= null ){
            		 target.addComponent(colorStoryChoice);
            	}
            }
        });
		brandChoice.setRequired( true );
		
		TextField identifier = new TextField( "identifier" );
		identifier.add( StringValidator.lengthBetween( 1, 255));
		identifier.setRequired( true );
		
		TextField earliestDeliveryDate = new TextField( "earliestDeliveryDate" );
		earliestDeliveryDate.setRequired( true );
		
		TextField discount = new TextField( "discount" );
		discount.setRequired( true );
		discount.add( NumberValidator.range( 0 , 100 ));
		
		TextField memberPrice = new TextField( "memberPrice" );
		memberPrice.setRequired( true );
		
		TextField price = new TextField( "price" );
		price.setRequired( true );
		
		TextField value = new TextField( "value" );
		value.setRequired( true );
		
		CompoundPropertyModel itemModel = new CompoundPropertyModel( item );
		
		itemForm = new Form( "itemForm", itemModel){
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit()
	        {

				
				Item item = (Item) itemForm.getModelObject();
				
				if( ! ( categoryChoice.getModelObject() instanceof SubCategory ) ){
					info( "Please choose a subcategory" );
					return;
				}
				
				item.setSubCategory( (SubCategory) categoryChoice.getModelObject() );
				
				if( ! item.hasGender() ){
					info( "You must choose at least one gender" );
					return;
				}
				
				if( item.getId() == null ){
					item.setAddedDate( new Date() );
					item.setCachedBalance( new Long(0));
				}
				getItemDao().save( item );
				info( "Item saved!" );
				getPage().addOrReplace( new ItemFragment("itemSelectionPanel",
"itemFragment"));
	        }
		};
		
		itemForm.add( colorStoryChoice  );
		itemForm.add( collectionChoice );
		itemForm.add( brandChoice ); 
		itemForm.add( categoryChoice ); 
		itemForm.add( memberPrice ); 
		itemForm.add( price ); 
		itemForm.add( value ); 
		
		itemForm.add( new CheckBox( "female" ) ); 
		itemForm.add( new CheckBox( "male" ) ); 
		itemForm.add( new CheckBox( "junior" ) );
		itemForm.add( identifier );
		itemForm.add( earliestDeliveryDate );
		itemForm.add( discount );
		add( itemForm );
		
		if( getItem().getId() != null  ){
			add( new ItemFragment("itemSelectionPanel", "itemFragment"));
		}else{
			add( new Label("itemSelectionPanel"));
		}
	}

	public Item getItem() {
		return item;
	}
	
	/**
	 * Fragment for adding , editing  translation for a
	 * store. 
	 * The item must exists before this fragment is visible.
	 * @author Mathias Nilsson
	 *
	 */
	private final class ItemFragment extends Fragment
	{
		private static final long serialVersionUID = 1L;
		public ItemFragment( String panel, String id ){
			super(panel, id, ItemPage.this );
			
			IModel availableStoresModel = new LoadableDetachableModel(){
				private static final long serialVersionUID = 1L;
				protected Object load()
				{
					return getStoreDao().getAvailableStores( getItem() );
				}
			};

			IModel unusedStoresModel = new LoadableDetachableModel(){
				private static final long serialVersionUID = 1L;
				protected Object load()
				{
					return getStoreDao().getUnusedStores( getItem() );
				}
			};
			final DropDownChoice availableStoresChoice = new DropDownChoice(
"availableStores", new Model( "" ),availableStoresModel, new
StoreChoiceRenderer()){
				private static final long serialVersionUID = 1L;
				
				@Override
				protected java.lang.CharSequence getDefaultChoice(final Object
selected){
					return "<option value=\"\">--- Edit item for store ---</option>"; 
				}
				 protected boolean wantOnSelectionChangedNotifications() {
					 
					 return true;
		         }
				 
				 protected void onSelectionChanged(final Object obj ) {
					 if( obj instanceof Store ){
						 Store store = (Store) obj;
						setResponsePage(  new ItemStorePage( getItem(), store ) );
					 }
		         }
				 
				 @Override
				 public boolean isVisible(){
					 if( getChoices().size() > 0 ){
						 return true;
					 }
					 return false;
				 }
			};
			final DropDownChoice unusedStoresChoice = new DropDownChoice(
"unusedStores", new Model( "" ),unusedStoresModel, new
StoreChoiceRenderer()){
				private static final long serialVersionUID = 1L;
				
				@Override
				protected java.lang.CharSequence getDefaultChoice(final Object
selected){
					return "<option value=\"\">--- New item for store ---</option>"; 
				}
				 protected boolean wantOnSelectionChangedNotifications() {
					 
					 return true;
		         }
				 
				 protected void onSelectionChanged(final Object obj ) {
					 if( obj instanceof Store ){
						 Store store = (Store) obj;
						 setResponsePage(  new ItemStorePage( getItem(), store ) );
					 }
		         }
				 
				 @Override
				 public boolean isVisible(){
					 if( getChoices().size() > 0 ){
						 return true;
					 }
					 return false;
				 }
				 
			};
			
			
			final IModel elementModel = new LoadableDetachableModel(){
				private static final long serialVersionUID = 1L;
				protected Object load()
				{
					return getCategoryDao().getElements( getItem().getSubCategory() );
				}
			};
			
			
			Form itemStoreForm = new Form( "itemStoreForm" );
			itemStoreForm.add( availableStoresChoice );
			itemStoreForm.add( unusedStoresChoice );
			
			Link attributeLink = new Link( "attributeLink" ){

				@Override
				public void onClick() {
					setResponsePage( new AttributePage( getItem() ) );
				}
				
				@Override
				public boolean isVisible(){
					List<Element> elements = (List<Element> )elementModel.getObject();
					if( elements == null || elements.size() == 0 ){
						return false;
					}
					
					return true;
				}
				
			};
			itemStoreForm.add( attributeLink );
			add( itemStoreForm );
			
		}
		
	}
}

And when adding translation to the item I get lazy loading exception
public class ItemStorePage extends BaseAdministrationPage {
	
	private Item item;
	private Store store;
	private ItemTranslation itemTranslation;
	

	public ItemStorePage( Item item, Store store ){
		this.item = item;
		this.store = store;
		
		initiateTranslation();
	

		final FeedbackPanel panel = new FeedbackPanel( "feedback" );
		panel.setOutputMarkupId(true);
		add( panel );
		
	

		Form itemForm = new Form( "itemForm", new CompoundPropertyModel(
getItemTranslation()) ){
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit()
	        {
				if( getItemTranslation().getId() == null ){
					/**
					 * Add Item to stort
					 */
					
					//getItem().addStore( getStore() );
					
					List<Store> stores = new LinkedList<Store>();
					stores.add( getStore() );
					getItem().setStores( stores );
					
					getItemDao().save( getItem() );
				}
				getTranslationDao().save(  getItemTranslation(), getItem() );
				info( "Item updated!" );
				
	        }
		};
		
		/** Adding data for translation */
		
		
		
		TextArea shortDescription = new TextArea( "shortDescription" );
		TextArea longDescription = new TextArea( "longDescription" );
		TextField name = new TextField( "name" );
		shortDescription.add( StringValidator.lengthBetween( 1, 500 ));
		shortDescription.setRequired( true );
		longDescription.add( StringValidator.lengthBetween( 1, 1000 ));
		longDescription.setRequired( true );
		name.add( StringValidator.lengthBetween( 1, 255 ));
		name.setRequired( true );
		itemForm.add( shortDescription );
		itemForm.add( longDescription );
		itemForm.add( name );
		add( itemForm );
		
		add( new Label( "itemId", getItem().getId().toString() ));
	}

	
	
	public void initiateTranslation(){


		itemTranslation = getTranslationDao().getTranslation( getStore(), getItem(
));
		
		if( itemTranslation == null ){
			itemTranslation = new ItemTranslation();
			itemTranslation.setItem( getItem() );
			itemTranslation.setStore( store );
		}
		
	}
	
	public Item getItem() {
		return item;
	}

	public Store getStore() {
		return store;
	}

	public ItemTranslation getItemTranslation() {
		return itemTranslation;
	}
}


-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17065528.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by Igor Vaynberg <ig...@gmail.com>.
where do you get the Item from when you pass it as constructor arg to
the page? and then in constructor of that page you try to access lazy
collections on item?

maybe if you posted some code we could help you better/faster.

-igor

On Mon, May 5, 2008 at 6:58 AM, Mathias P.W Nilsson
<ma...@snyltarna.se> wrote:
>
>  Hi!
>
>  I will check out the Object that was posted thanks!
>
>  Yes I put the opensessioninview filter before.
>
>  I think the problem is this.
>
>  Lets say I list all of my items in one page.
>
>  Name, Description
>  TestName, TestDescription
>
>  When clicking the name link I do the following
>
>  setResponsePage( new ItemPage( item ) );
>
>  I pass the item object to the constructor. The item has references to store
>  and some other objects.
>  The store is never loaded in the previous page and to do
>  item.getStore().getId() is impossible I will get a lazy loading exception.
>  What is the solution to this.
>
>  I have downloaded the wicket phonebook and see that the id is passed to the
>  constructor.
>
>  Do you always load every object that has a reference to an entity? Example
>  ItemTranslation has reference to Store, Item
>
>  When editing a ItemTranslation I will pass the object to the Wicket page
>  constructor. The store and item is not loaded since they are lazy.
>
>  What is the approach here? load the store and the item and set them in the
>  ItemTranslation? This sounds very tedious¨. Any other suggestions. The lazy
>  loading exception occurs when the entity has reference to lazy entities that
>  is not loaded in the page.
>
>
>  --
>  View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17062281.html
>
>
> Sent from the Wicket - User mailing list archive at Nabble.com.
>
>
>  ---------------------------------------------------------------------
>  To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
>  For additional commands, e-mail: users-help@wicket.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by James Carman <ja...@carmanconsulting.com>.
On Mon, May 5, 2008 at 9:58 AM, Mathias P.W Nilsson
<ma...@snyltarna.se> wrote:
>
>  Hi!
>
>  I will check out the Object that was posted thanks!
>
>  Yes I put the opensessioninview filter before.
>
>  I think the problem is this.
>
>  Lets say I list all of my items in one page.
>
>  Name, Description
>  TestName, TestDescription
>
>  When clicking the name link I do the following
>
>  setResponsePage( new ItemPage( item ) );
>

Try using a bookmarkable page link and just pass in the item's id?

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
Hi!

I will check out the Object that was posted thanks!

Yes I put the opensessioninview filter before.

I think the problem is this.

Lets say I list all of my items in one page. 

Name, Description
TestName, TestDescription

When clicking the name link I do the following 

setResponsePage( new ItemPage( item ) );

I pass the item object to the constructor. The item has references to store
and some other objects.
The store is never loaded in the previous page and to do
item.getStore().getId() is impossible I will get a lazy loading exception.
What is the solution to this.

I have downloaded the wicket phonebook and see that the id is passed to the
constructor.

Do you always load every object that has a reference to an entity? Example
ItemTranslation has reference to Store, Item 

When editing a ItemTranslation I will pass the object to the Wicket page
constructor. The store and item is not loaded since they are lazy.

What is the approach here? load the store and the item and set them in the
ItemTranslation? This sounds very tedious¨. Any other suggestions. The lazy
loading exception occurs when the entity has reference to lazy entities that
is not loaded in the page. 


-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17062281.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
Please do. This would be very helpful.

In my former ( first ) wicket application I used dto's but I would like to
use detached hibernate objects instead for this project.

Your posts has been most helpful.
-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17053990.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by Igor Vaynberg <ig...@gmail.com>.
you still have something misconfigured or you are not using detachable
models where you should. ive built plenty of hibernate+spring+wicket
apps to know that it works just fine and is pretty easy to do. if you
want you can post a quickstart that demonstrates your problem and
someone might be able to help you.

-igor


On Sun, May 4, 2008 at 10:01 AM, Mathias P.W Nilsson
<ma...@snyltarna.se> wrote:
>
>  I have session in view filter but still gets LazyLoadingException even if I
>  use detached models! Ahhh...
>
>  Solved it temporarily by using Eager fetch but this is going to end up bad
>  if everything is eager.
>  --
>  View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17048739.html
>
>
> Sent from the Wicket - User mailing list archive at Nabble.com.
>
>
>  ---------------------------------------------------------------------
>  To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
>  For additional commands, e-mail: users-help@wicket.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
I have session in view filter but still gets LazyLoadingException even if I
use detached models! Ahhh... 

Solved it temporarily by using Eager fetch but this is going to end up bad
if everything is eager. 
-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17048739.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by Stefan Fußenegger <st...@gmx.at>.
Do you have OpenSessionInViewFilter in your web.xml? If no, you will get this
exception whenever you try to do lazy loading outside your DAOs.

add to web.xml:
  <filter>
    <filter-name>OpenSessionFilter</filter-name>
    <filter-class>
      org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    </filter-class>
    <init-param>
      <param-name>sessionFactoryBeanName</param-name>
      <param-value>hibernateSessionFactory</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>OpenSessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

I always use a self-written class called PersistentObjectModel (a
LoadableDetachableModel) and let all my Persisent classes implement an
interface called IPersistentObject with a single method: Serializable
getId()

public class PersistentObjectModel<T extends IPersistentObject> extends
LoadableDetachableModel {

	private static final long serialVersionUID = 1L;

	private final Class<T> _clazz;

	private final int _id;

	@SpringBean(name = "myDao")
	private IMyDao _myDao;

	@SuppressWarnings("unchecked")
	public PersistentObjectModel(final T object) {
		super(object);

		if (object instanceof HibernateProxy) {
			_clazz = (Class<T>) ((HibernateProxy)
object).getHibernateLazyInitializer()
					.getImplementation().getClass();
		} else {
			_clazz = (Class<T>) object.getClass();
		}
		_id = object.getId();
		// inject the bean
		InjectorHolder.getInjector().inject(this);
	}

	public PersistentObjectModel(final Class<T> clazz, final int id) {
		_clazz = clazz;
		_id = id;
		// inject the bean
		InjectorHolder.getInjector().inject(this);
	}

	@Override
	protected T load() {
		return _myDao.getById(_clazz, _id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getObject() {
		return (T) super.getObject();
	}

}


This makes working with hibernate objects really easy:

setModel(new PersistentObjectModel(Foo.class, 1)); // option 1: class and id
setModel(new PersistentObjectModel(foo)); // option 2: persistent object

-----
-------
Stefan Fußenegger
http://talk-on-tech.blogspot.com // looking for a nicer domain ;)
-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17045620.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
I have a page that list a Items that is hibernated annotated. When clicking
on a wicket link
using setResponsePage( new ItemPage( item ) ); I get the exception when
trying to render my DropDownChoice. 

I use Detached model for this. load is not called, if you mean
hibernatesession.load or entitymanager.load
-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17045071.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by Johan Compagner <jc...@gmail.com>.
for which request does it through there the exception?
first you render it ? then you change it and it throws the exception on the
second request?
does load get called at that point?

On Sun, May 4, 2008 at 12:37 PM, Mathias P.W Nilsson <ma...@snyltarna.se>
wrote:

>
> Thanks!
>
> This is what I'm trying to do but I still get the exception.
>
> This is from my DAO
>
> @SuppressWarnings( "unchecked" )
> public List<Collection> getCollections(){
>   org.hibernate.Session hibernateSession =
> (org.hibernate.Session)getEntityManager().getDelegate();
>   return hibernateSession.createCriteria Collection.class
>
> ,se.edgesoft.hairless.model.criteria.alias.Alias.COLLECTION.getAlias()).list();
> }
>
> I use the
> org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
> before the wicket filter.
> This is Entity manager and not sessionInView.
>
> In my base class I spring inject my dao's using @SpringBean annotation.
>
> Here is the model I'm using
>
> IModel collectionModel = new LoadableDetachableModel(){
>  private static final long serialVersionUID = 1L;
>  protected Object load(){
>    return getCollectionDao().getCollections();
>  }
> };
>
>
> And it complains in my renderer
>
> public class CollectionChoiceRenderer extends ChoiceRenderer {
>        private static final long serialVersionUID = 1L;
>        public Object getDisplayValue(Object object) {
>        if (object instanceof Collection) {
>                Collection  collection = ( Collection ) object;
>
>                return collection.getIdentifier();
>        }
>        return null;
>    }
>    public String getIdValue(Object key, int index) {
>        if (key instanceof Collection) {
>                Collection collection = ( Collection ) key;
>            return collection.getId().toString();
>        }
>        return null;
>    }
> }
>
> Lazy loading exception when I try collection.getId().toString()
>
> I thought this was detaching hibernate entities. The Collection class is a
> hibernate annotated pojo.
>
>
> --
> View this message in context:
> http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17044892.html
> Sent from the Wicket - User mailing list archive at Nabble.com.
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
> For additional commands, e-mail: users-help@wicket.apache.org
>
>

Re: How to avoid Lazy loading exception

Posted by "Mathias P.W Nilsson" <ma...@snyltarna.se>.
Thanks!

This is what I'm trying to do but I still get the exception.

This is from my DAO

@SuppressWarnings( "unchecked" )
public List<Collection> getCollections(){
   org.hibernate.Session hibernateSession =
(org.hibernate.Session)getEntityManager().getDelegate();
   return hibernateSession.createCriteria Collection.class 
,se.edgesoft.hairless.model.criteria.alias.Alias.COLLECTION.getAlias()).list();
}

I use the org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
before the wicket filter.
This is Entity manager and not sessionInView.

In my base class I spring inject my dao's using @SpringBean annotation.

Here is the model I'm using

IModel collectionModel = new LoadableDetachableModel(){
  private static final long serialVersionUID = 1L;
  protected Object load(){
    return getCollectionDao().getCollections();
  }
};


And it complains in my renderer

public class CollectionChoiceRenderer extends ChoiceRenderer {
	private static final long serialVersionUID = 1L;
	public Object getDisplayValue(Object object) {
        if (object instanceof Collection) {
        	Collection  collection = ( Collection ) object;
        	
        	return collection.getIdentifier();
        }
        return null;
    }
    public String getIdValue(Object key, int index) {
        if (key instanceof Collection) {
        	Collection collection = ( Collection ) key;
            return collection.getId().toString();
        }
        return null;
    }
}

Lazy loading exception when I try collection.getId().toString()

I thought this was detaching hibernate entities. The Collection class is a
hibernate annotated pojo.


-- 
View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17044892.html
Sent from the Wicket - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org


Re: How to avoid Lazy loading exception

Posted by Igor Vaynberg <ig...@gmail.com>.
this is not very difficult to fix. there are really only two basic rules:
1) never keep direct references to hibernate entities. this is because
they will become detached between request and unless you call
session.lock/refresh on them before accessing a collection you will
get the lazy exception. instead, use detachable models such as the
loadabledetachablemodel to give components access to entities.

2) install spring's opensessioninview filter that runs around the
wicket filter. by default spring's transactionam support will create a
session per transaction, by the time wicket will render the page the
session will be closed along with the transaction. having the filter
will ensure spring uses session-per-request pattern and reuse the same
session for multiple transactions when possible. since the filter is
around wicket's the session will still be open when wicket renders the
page.

for an example you can see wicket-phonebook app in wicket-stuff's svn.

-igor


On Sat, May 3, 2008 at 4:20 PM, Mathias P.W Nilsson
<ma...@snyltarna.se> wrote:
>
>  Is there any good tutorial on wicket, hibernate and spring? When dealing with
>  my lazy many to one relations I get lazy loading exception. Very annoing.
>
>  Lets say I have an Item class that has many to one relations to a category.
>  I list the items in a wicket page and when click a link I do
>  setResponsePage( new ItemPage( item ) );
>
>  when getting to this page I get a lazy loading exception on the category.
>  How's that? I thought that open session in view should allow this. Is there
>  any way of dealing with this?
>  --
>  View this message in context: http://www.nabble.com/How-to-avoid-Lazy-loading-exception-tp17040941p17040941.html
>  Sent from the Wicket - User mailing list archive at Nabble.com.
>
>
>  ---------------------------------------------------------------------
>  To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
>  For additional commands, e-mail: users-help@wicket.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@wicket.apache.org
For additional commands, e-mail: users-help@wicket.apache.org