Hibernate recursive many-to-many association with the same entity

后端 未结 3 732
一生所求
一生所求 2020-11-28 21:07

Another Hibernate question... :P

Using Hibernate\'s Annotations framework, I have a User entity. Each User can have a collection of friends

3条回答
  •  温柔的废话
    2020-11-28 21:15

    Actually its very simple and could be achieved by following say you have following entity

    public class Human {
        int id;
        short age;
        String name;
        List relatives;
    
    
    
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public short getAge() {
            return age;
        }
        public void setAge(short age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public List getRelatives() {
            return relatives;
        }
        public void setRelatives(List relatives) {
            this.relatives = relatives;
        }
    
        public void addRelative(Human relative){
            if(relatives == null)
                relatives = new ArrayList();
            relatives.add(relative);
        }
    
    
    
    
    }
    

    HBM for same:

    
        
            
                
                
            
            
                
            
            
                
            
            
             
             
             
          
        
    
    

    And test case

    import org.junit.Test;
    import org.know.common.HBUtil;
    import org.know.july31.hb.Human;
    
    public class SimpleTest {
    
        @Test
        public void test() {
            Human h1 = new Human();
            short s = 23;
            h1.setAge(s);
            h1.setName("Ratnesh Kumar singh");
            Human h2 = new Human();
            h2.setAge(s);
            h2.setName("Praveen Kumar singh");
            h1.addRelative(h2);
            Human h3 = new Human();
            h3.setAge(s);
            h3.setName("Sumit Kumar singh");
            h2.addRelative(h3);
            Human dk = new Human();
            dk.setAge(s);
            dk.setName("D Kumar singh");
            h3.addRelative(dk);
            HBUtil.getSessionFactory().getCurrentSession().beginTransaction();
            HBUtil.getSessionFactory().getCurrentSession().save(h1);
            HBUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
            HBUtil.getSessionFactory().getCurrentSession().beginTransaction();
            h1 = (Human)HBUtil.getSessionFactory().getCurrentSession().load(Human.class, 1);
            System.out.println(h1.getRelatives().get(0).getName());
    
            HBUtil.shutdown();
        }
    
    }
    

提交回复
热议问题