我有一个JPA实体“Food”,它有一个字段“idPtr”,我想根据“code”字段的值Map到“Vegetable”实体或“Fruit”实体。以下是我目前掌握的信息:
@Getter
@Setter
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "code")
private String code;
@Column(name = "ptr_id")
private Integer idPtr;
// ...
}
我想修改“idPtr”字段为Vegetable或Fruit实体,具体取决于代码字段的值,以便具有如下内容:
@Getter
@Setter
@Entity
@Table(name = "food")
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "code")
private String code;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ptr_id", referencedColumnName = "id", insertable = false, updatable = false)
private Vegetable ptrVegetable;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ptr_id", referencedColumnName = "id", insertable = false, updatable = false)
private Fruit ptrFruit;
// ...
}
条件应该类似于if(“VEG”.equals(code)),然后我们将这个Food与实体Vegetable连接起来
1条答案
按热度按时间ktca8awb1#
我想你可以用Single Table inheritance strategy。在这种情况下,
Food
实体应该有两个继承者。第一个连接Vegetable
,第二个连接Fruit
。看看下面的代码示例。