Hibernate一对一映射双向

时间:2012-11-15 10:37:59

标签: hibernate mapping one-to-one

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。 怎么避免这个?

2 个答案:

答案 0 :(得分:1)

让我们从更具描述性的映射开始,然后我们可以删除部分,无论如何都会将其重新设置为默认值。

有一个比我的摘录更详细的描述。请看一下: 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"
           , parameters=@Parameter(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级联功能将为我们提供其余功能

答案 1 :(得分:0)

看起来很俗气,但试着

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