Hibernate多对多双向关联映射

                              Hibernate多对多双向关联映射

1、数据库结构

       category表:{ categoryId , categoryName }

       item表:{ itemId , itemName }

       category_item表:{ idCategory , idItem}

2、Category.hbm.xml

< hibernate-mapping >
    
< class  name ="com.persistent.Category"  table ="category" >
        
< id  name ="id"  column ="categoryId"  unsaved-value ="null" >
            
< generator  class ="increment" ></ generator >
        
</ id >
        
< property  name ="name"  column ="categoryName" ></ property >
        
< set  name ="items"  table ="category_item"  cascade ="all"  lazy ="false" >
            
< key  column ="idCategory" ></ key >
            
< many-to-many  class ="com.persistent.Item"  column ="idItem" ></ many-to-many >
        
</ set >
    
</ class >
</ hibernate-mapping >

3、Item.hbm.xml

< hibernate-mapping >
    
< class  name ="com.persistent.Item"  table ="item" >
        
< id  name ="id"  column ="itemId"  unsaved-value ="null" >
            
< generator  class ="increment" ></ generator >
        
</ id >
        
< property  name ="name"  column ="itemName" ></ property >
        
< set  name ="categories"  table ="category_item"  lazy ="false"  inverse ="true" >
            
< key  column ="idItem" ></ key >
            
< many-to-many  class ="com.persistent.Category"  column ="idCategory" ></ many-to-many >
        
</ set >
    
</ class >
</ hibernate-mapping >

4、Category.java和Item.java

public   class  Category  {    
private Long id;
    private String name;
private Set items = new HashSet();
...
}


public   class  Item  {
private Long id;
private String name;
private Set categories = new HashSet();
...
}

    

      映射文件中还可以不用set而用bag,只要把set出现的地方改成bag就行,这样相应的category.java和Item.java

文件当中就可以用List。

你可能感兴趣的:(Hibernate,数据库,table,null,Class,generator)