欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate OneToOne关联

程序员文章站 2022-04-22 16:10:33
...
  • 单向-共享主键
//Address不包含任何到User的信息
//使用optional=false,确定addr非空,这样hibernate不用检查addr是否为空,才能使用懒加载
//使用@PrimaryKeyJoinColumn使用Address的主键作为User的外键以及主键
//添加时需要先添加Address再添加User,并手动设置user.setId(addr.getId())
@Entity
class User{
  //不指定生成策略
  @Id
  private long id;
  @OneToOne(
  fetch = FetchType.LAZY,
  optional = false)
  @PrimaryKeyJoinColumn
  private Address addr;
}
//表结构
|       user               |address|
|id<pk><fk_from_address_id>|id|
  • 双向-共享主键
@Entity
class User{
    @Id
    @GeneratedValue(generator = "addressKeyGenerator")
    @org.hibernate.annotations.GenericGenerator(
    name = "addressKeyGenerator",
    strategy = "foreign",
    parameters =
    @org.hibernate.annotations.Parameter(
            name = "property", value = "addr"
        )
    )
  private long id;
  @OneToOne(
  fetch = FetchType.LAZY,
  optional = false)
  @PrimaryKeyJoinColumn
  private Address addr;
}
@Entity
class Address{
    @Id
    @GeneratedValue
    private long id;
    @OneToOne(
    mappedBy = "addr",
    cascade = CascadeType.PERSIST)
    private User user;
}
//表结构
|       user               |address|
|id<pk><fk_from_address_id>|id|
  • 不共享主键只要将@PrimarKeyJoinColumn改为@JoinColumn,并各自指定生成策略即可。
表结构
|  user  |address|
| id     | id |
|a_id<fk>| -  |
  • 通过将@JoinColumn改为@JoinTable,可以使用关联表进行关联。
@Entity
public class Shipment {
  @OneToOne(fetch = FetchType.LAZY)
  @JoinTable(
    name = "ITEM_SHIPMENT",
    joinColumns = @JoinColumn(name = "SHIPMENT_ID"),
    inverseJoinColumns = @JoinColumn(
      name = "ITEM_ID",
      nullable = false,
      unique = true)
    )
  protected Item auction;
// ...
}