Hibernate-one to one

  • db table
CREATE TABLE HUSBAND
(
  HUSBAND_ID       NUMBER(5)    NOT NULL,
  NAME          VARCHAR(20)  
)
CREATE TABLE WIFE
(
  WIFE_ID       NUMBER(5)    NOT NULL,
  HUSBAND_ID       NUMBER(5)    NOT NULL,
  NAME          VARCHAR(20)  
)
  • hibernate.cfg.xml



    
        oracle.jdbc.OracleDriver
        *****
        jdbc:oracle:thin:@DbServer:port:sid
        ***
        org.hibernate.dialect.Oracle10gDialect
        
        true
        true
        
        
        
    

  • Husband.hbm.xml



    
        
            
            
        
        
            
        
    

  • Wife.hbm.xml



    
        
            
            
        
        
            
        
        
    

  • POJO
package pojo.oneToOneConfig;

public class Husband {

    private int husbandId;
    private String name;
    private Wife wife;
    //getter and setter

}
package pojo.oneToOneConfig;

public class Wife {

    private int wifeId;
    private String name;
    private Husband husband;
    //getter and setter
}
  • HibernateUtil

改成注解的版本:

  • hibernate.cfg.xml



    
        oracle.jdbc.OracleDriver
        *****
        jdbc:oracle:thin:@DbServer:port:sid
        ***
        org.hibernate.dialect.Oracle10gDialect
        
        true
        true
        
        
        
    

  • POJO
package pojo.oneToOneAnnotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="HUSBAND")
public class Husband {

    @Id
    @Column(name="HUSBAND_ID")
    private int husbandId;
    @Column(name="NAME")
    private String name;
    @OneToOne(mappedBy="husband") // the husband property in Wife
    private Wife wife;
    //getter and setter
 
}
package pojo.oneToOneAnnotation;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "WIFE")
public class Wife {

    @Id
    @Column(name = "WIFE_ID")
    private int wifeId;
    @Column(name = "NAME")
    private String name;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "HUSBAND_ID")
    private Husband husband;
    //getter and setter

}

你可能感兴趣的:(Hibernate-one to one)