我有三个表:
CREATE TABLE book (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
title VARCHAR(256),
...
PRIMARY KEY (`id`)
)
CREATE TABLE book_extras (
id BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
book_extra_type VARCHAR(20),
book_id INT NOT NULL,
...
PRIMARY KEY(id),
KEY fk_book_extras_books (book_id),
CONSTRAINT fk_book_extras_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE ON
UPDATE CASCADE
)
CREATE TABLE book_cd (
id BIGINT(20) unsigned NOT NULL,
singer VARCHAR(100) NOT NULL,
...
PRIMARY KEY (`id`),
CONSTRAINT `FK_book_cd_book_extras` FOREIGN KEY (`id`)
REFERENCES `book_extras` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
对于每个表,我都有一个实体类:
@Entity
@Table(name = "book")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Book{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "book")
private List<BookExtra> bookExtras;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL)
private List<BookCd> cds= new ArrayList<>();
...
}
@Entity
@Table(name = "book_extras")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "book_extra_type")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookExtra {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
protected Long id;
@JoinColumn(name = "book_id", referencedColumnName = "id")
@ManyToOne
protected Book book;
...
}
@Entity
@Table(name = "book_cd")
@PrimaryKeyJoinColumn(name = "id")
@DiscriminatorValue("CD")
@Data
public class BookCd extends BookExtra {
@Column(name = "singer", length = 100)
private String singer;
}
保存数据后,一切都很好,我将所有三个表都填满,book_extras和book_cd表中的id相等,book_extra_type设置为CD
。
当我想从Book实体访问CD的收藏集时出现问题:
Book b = <get the book from db>;
List<BookCd> cds = b.getCds();
我收到一个错误:java.sql.SQLException: Unknown column 'cds0_.book_id' in 'field list'
。似乎休眠状态正在将指向book_cd的外键指向book表,但是它们之间有book_extras表。您能帮忙告诉我如何正确地从Book类访问CD收藏吗?