[jboss-user] [Persistence, JBoss/CMP, Hibernate, Database] - Bidirectional onetomany relationship doesn't work

cold80 do-not-reply at jboss.com
Thu Feb 15 08:04:55 EST 2007


I'm really getting crazy. This is my first experience with EJB and 
JBoss (and Hibernate as well actually) but I'm finding a lot of 
problems even with the easy stuff!!! I wanna set up a one-to-many 
relationship between two entities, but this relationship is supposed 
to be bidirectional. I have a "site" entity and a "item" entity and I 
want to say that every site can have more than one entity. But I would 
like to access the sites linked to an entity from the item object and 
viceversa. These are the code fragments: 

Site.java 


@OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY,mappedBy="site") 
    public java.util.Collection getItems(){ 
        return this.items; 
    } 


    public void setItems(Collection items){ 
        this.items=items; 
    } 


Item.java 


@ManyToOne 
    public Site getSite(){ 
        return this.site; 
    } 


    public void setSite(Site site){ 
        this.site=site; 
    } 


This operation seems to work actually. Jboss creates a column 
"site_id" on the items table and if I run this code 


Item item=new Item(); 
Site site=new Site(); 
item.setSite(site); 
manager.persist(site); 
manager.persist(item); 


I find that the "items" table contains a record, and it is mapped to 
the new record I can find on the "sites" table. The problem is that if 
I check the value for site.getItems() after the persist operation I 
get a null value. It seems that the opposite "relationship" is not set 
properly. I get a problem even if I don't persist the site before the 
item and I can't understand why...isn't Hibernate supposed to persist 
automatically the site entity by itself? Maybe I'm using badly the 
annotation, please help me!!! 


Can some of you explain me if it's possible with Hibernate to define a 
many-to-many relationship with some relationship attributes and a many- 
to-one relationship that connects an entity with itself (in order to 
build a tree)? 


Thank you in advance for your help 


Cold


View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4016999#4016999

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4016999



More information about the jboss-user mailing list