2023年12月8日 问题: Entity Car 有两类Entity BigCar 及Entity SmallCar; 数据库中对应三张表 car 、small_car、big_car 。 采用 @OneToOne 之类的做法会造成 query list 时 N 次查询问题(如 car list 有 10条,则需要查询 11 次 sql) 解决: 可以调整 Entity 通过 JPA 继承的方式解决 @Data @Table(name = "car") @Entity @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING) public class Event implements Serializable { @Serial private static final long serialVersionUID = 1L; @Id @Column(name = "id", nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer eventId; } @Data @Entity @Table(name = "small_car") @DiscriminatorValue("smallcar") @PrimaryKeyJoinColumn(name="car_id") public class SmallCar extends Car { ... } @Data @Entity @Table(name = "big_car") @DiscriminatorValue("bigcar") @PrimaryKeyJoinColumn(name="car_id") public class BigCar extends Car { ... } 123456789101112131415161718192021222324252627282930313233343536 @Data@Table(name = "car")@Entity@Inheritance(strategy = InheritanceType.JOINED)@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)public class Event implements Serializable { @Serial private static final long serialVersionUID = 1L; @Id @Column(name = "id", nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer eventId;} @Data@Entity@Table(name = "small_car")@DiscriminatorValue("smallcar")@PrimaryKeyJoinColumn(name="car_id")public class SmallCar extends Car {...} @Data@Entity@Table(name = "big_car")@DiscriminatorValue("bigcar")@PrimaryKeyJoinColumn(name="car_id")public class BigCar extends Car {...} 这样 query list 会使用 join 的方式一条sql 取出结果 参考: 《Pro JPA2 中文版: 精通Java 持久化API》 p289