users@glassfish.java.net

Many to Many bidirectional relationship

From: <glassfish_at_javadesktop.org>
Date: Thu, 08 Mar 2007 12:28:51 PST

[b]I’m trying to set up a Many-To-Many relationship between two entities. I believe I have set it up correctly and they persist to the database fine, where by I get two entity tables and a relationship table mapping them together via there PK. However if I want to access a collection in one of the entities with a getCollectionEG method it always returns an empty collection. My code is as follows:

Owning side entity Story.java contains a Collection and annotations:[/b]

  private Collection<TestTable> testTables = new ArrayList<TestTable>();


 @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
 @JoinTable(name="STORY_TESTTABLE",
    joinColumns=_at_JoinColumn(name="STORY_ID",
                                                            referencedColumnName="STORY_ID"),
            inverseJoinColumns=_at_JoinColumn(name="TABLE_ID",
                                                            referencedColumnName="TABLE_ID"))
   public Collection<TestTable> getTestTables(){
        return testTables;
   }

[b]The other entity has a Collection and the annotation mapping:[/b]

private Collection<Story> stories = new ArrayList<Story>();
   
@ManyToMany(mappedBy="testTables",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    public Collection<Story> getStories(){
        return stories;
    }

[b]I have a TestTableFacade which contains a create method:[/b]

public void create(TestTable testTable) throws PageDoesNotExistException, TableCouldNotBeAddedToHTMLFileException, TestTableDoesNotExistException {
        Page pageFound = null;
        try {
            pageFound = page.findByName(testTable.getP().getPageName());
            testTable.setP(pageFound);
        } catch (QueryDidNotReturnResultException ex) {
            throw new PageDoesNotExistException();
        }

int position = -1;
        
        Collection<Story> storiesToBeAdded = new ArrayList<Story>();
        
        ArrayList<Story> theStories = (ArrayList) testTable.getStories();
        if((theStories.size() > 0) && (!theStories.get(0).getStoryName().equals(""))){
            Collection<Story> stories = new ArrayList<Story>(theStories);
            
            for(Story s: stories){
                try {
                    Story storyFound = story.findStoryByName(s.getStoryName());
                    storiesToBeAdded.add(storyFound);
                    
                    if(position == -1){
                        position = storyFound.getId().intValue();
                    }
                } catch (StoryNotFoundException ex) {
                    ex.printStackTrace();
                }
            }
        }else{
            position = -1;
        }
        testTable.setStories(storiesToBeAdded);
               
        em.persist(testTable);
        em.flush();

for(Story s: testTable.getStories()){
            try {
                if(s != null && !s.equals("")){
                    Story st = story.findStoryByName(s.getStoryName());
                    
                    st.getTestTables().add(this.findTableByName(testTable.getTableName()));
                    
                    em.merge(st);
                }
            } catch (StoryNotFoundException ex) {
                ex.printStackTrace();
            } catch (TestTableDoesNotExistException ex) {
                ex.printStackTrace();
            }
        }

}

[b]So as far as I can see I do everything correctly. The Database is created correctly, the data is stored correctly with the relationship shown. I even have a EJB QL statement which gets testTables. Which returns me the list of testTables inside a given story.[/b]

Query query = em.createQuery( "SELECT o.testTables FROM Story o WHERE o.id=?1");
       query.setParameter(1, id);
       return query.getResultList();


[b]However if I find a Story entity and call getTestTables(), it always returns an empty collection. I would be very grateful for any suggestions.[/b]

[b]Thanks[/b]
[Message sent by forum member 'ptm' (ptm)]

http://forums.java.net/jive/thread.jspa?messageID=206968