@Embeddable
表示这个类可以被嵌入,如A–》 C,C类上如果不加这个注解,使用 @Embedded
嵌入到A类的时候没问题。但是如果一对多嵌入,就会报错:
@ElementCollection
@CollectionTable(
name = "book_author",
joinColumns = @JoinColumn(name = "book_id")
)
@Embedded
表示这个类被嵌入,如果是一对一嵌入的话,在A中给C加上这个注解即可。
其实为了保险起见,2个都用最好。
Author
类代码:
@Data
@Embeddable
@Access( AccessType.PROPERTY )
public class Author {
private String firstName;
private String lastName;
public Author(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
Book
类代码:
@Data
@Entity(name = "Book")
public class Book {
@Id
private Long id;
private String title;
@ElementCollection
@CollectionTable(
name = "book_author",
joinColumns = @JoinColumn(name = "book_id")
)
private List<Author> authors = new ArrayList<>();
}
生成数据库如图: