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();

虽然我从孩子设置了父母,但该列仍然是空的,我得到空值。如何避免这种情况?

4

2 回答 2

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 级联功能将由我们来完成

于 2012-11-16T07:06:42.043 回答
0

看起来俗气但尝试

public void setDriver(Driver driver){
    this.driver = driver;
    driver.setLicense(this);
}
于 2012-11-16T06:51:21.863 回答