hibernate中one-to-one两种配置方式

public class Person {  
    private int id;  
    private String name;  
    private IdCard idCard;  
  
    public Person() {  
    }  
  
    public Person(int id, String name, IdCard idCard) {  
        this.id = id;  
        this.name = name;  
        this.idCard = idCard;  
    }  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public IdCard getIdCard() {  
        return idCard;  
    }  
  
    public void setIdCard(IdCard idCard) {  
        this.idCard = idCard;  
    }  
  
}  

public class IdCard {  
    private int id;  
    private Date usefullLife;  
    private Person person;  
  
    public IdCard() {  
    }  
  
    public IdCard(int id, Date usefullLife, Person person) {  
        this.id = id;  
        this.usefullLife = usefullLife;  
        this.person = person;  
    }  
  
    public int getId() {  
        return id;  
    }  
  
    public void setId(int id) {  
        this.id = id;  
    }  
  
    public Date getUsefullLife() {  
        return usefullLife;  
    }  
  
    public void setUsefullLife(Date usefullLife) {  
        this.usefullLife = usefullLife;  
    }  
  
    public Person getPerson() {  
        return person;  
    }  
  
    public void setPerson(Person person) {  
        this.person = person;  
    }  
  
}  



one-to-one方式一:


IdCard.hbm.xml

  
  
      
  
  
      
          
              
              
                person  
              
          
          
          
              
          
          
          
      
  


Person.hbm.xml

  
  
      
  
  
      
          
              
              
          
          
          
              
          
          
          
      
  




one-to-one方式二:


IdCard.hbm.xml

  
  
      
  
  
      
          
          
           
           
          
          
          
              
          
          
  
          
      
  



Person.hbm.xml

  
  
      
  
  
      
          
              
              
          
          
          
              
          
          
          
      
  


测试:

        Session s = null;  
        try{  
            s = HibernateSessionFactory.getSession();  
//          Person person = (Person)s.get(Person.class, id);  
//          System.out.println(person.getIdCard().getUsefullLife());  
              
            IdCard idCard = (IdCard)s.get(IdCard.class, id);  
            System.out.println(idCard.getPerson().getName());  
              
        } catch (HibernateException e) {  
            e.printStackTrace();  
        }  



你可能感兴趣的:(Hibernate)