Hibernate/JPA中@OneToOne和@MapsId的使用
程序员文章站
2022-04-12 17:45:25
...
Hibernate/JPA中@OneToOne和@MapsId的使用
双向@OneToOne的效率低于与父表共享主键的单向@OneToOne。因此,不要使用双向@OneToOne,最好是依靠单向@OneToOne和@MapsId。第一步:在子实体这边使用@MapsId基本上,上面@OneToOne关联,它将与父表共享主键,父实体见如下,父实体中没有@OneToOne,这说明是从子实体指向父实体的单向关联;
第一步:在子实体这边使用@MapsId:
@Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "title", nullable = false)
private String title;
@Column(name = "description")
private String description;
@Column(name = "publication_date")
private LocalDate publicationDate;
@Column(name = "price", precision = 21, scale = 2)
private BigDecimal price;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Author author;
基本上,上面@OneToOne关联,它将与父表共享主键,父实体见如下,父实体中没有@OneToOne,这说明是从子实体指向父实体的单向关联:
@Entity
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "birth_date")
private LocalDate birthDate;