2012-11-15 199 views
1
public class Driver { 

    @OneToOne 
    private License license; 

    //.. getter setter 
}; 

public class License { 

    @OneToOne(mappedBy='license') 
    private Driver driver; 

    //.. getter setter 
} 

我通過此映射在Db的驅動程序表中獲取連接列license_id。問題是:休眠一對一映射雙向

Driver driver = new Driver(); 
// save driver then get it etc... 

License license = new License(); 
license.setDriver(driver); 
// save license... 

driver.getLicense(); 

儘管我從child設置父項,列仍然是空的,我得到null。 如何避免這種情況?

+0

節省許可證與驅動程序後,你從數據庫許可加載的驅動程序? – RAS

+0

是的,我做到了,但沒有奏效。 – thetux4

+0

那麼在那種情況下,我想我需要看完整的代碼。你可以發佈第二部分的代碼嗎? – RAS

回答

0

看起來俗氣,但嘗試

public void setDriver(Driver driver){ 
    this.driver = driver; 
    driver.setLicense(this); 
} 
1

讓我們開始更多的描述映射,我們以後可以去除的部分,這將是無論如何relaized爲默認值。

有一個描述比我的提取更詳細。請它來看一看: http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/

此基礎上,讓我們擴展映射是這樣的:

司機

public class Driver { 

    @Id 
    @GeneratedValue 
    @Column(name="driver_id") 
    private Long driverId;  

    // cascade will do the job for us 
    @OneToOne(mappedBy="driver", cascade=CascadeType.ALL) 
    private License license; 

許可證

public class License { 

    @Id 
    @Column(name="driver_id", unique=true, nullable=false) 
    @GeneratedValue(generator="gen") 
    @GenericGenerator(name="gen", strategy="foreign" 
      , [email protected](name="property", value="driver")) 
    private Long driverId; 

    @OneToOne 
    @PrimaryKeyJoinColumn 
    private Driver driver 
    ... 

當插入新的價值,我們可以明確設置兩端:

Driver driver = new Driver(); 
License license = new License(); 
// set both ends 
license.setDriver(driver); 
driver.setLicense(license); 

// Just save the Driver. the cascade will do the rest 

現在Hibernate的級聯功能,將其餘的爲我們