java 如何根据条件将JPA实体字段Map到不同的实体类型?

3ks5zfa0  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(102)

我有一个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连接起来

ktca8awb

ktca8awb1#

我想你可以用Single Table inheritance strategy。在这种情况下,Food实体应该有两个继承者。第一个连接Vegetable,第二个连接Fruit。看看下面的代码示例。

@Getter
@Setter
@Entity
@Table(name = "food")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="code", 
  discriminatorType = DiscriminatorType.STRING)
class Food {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "code")
    private String code;
}

@Entity
@DiscriminatorValue("VEG")
class VegetableFood extends Food {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ptr_id", referencedColumnName = "id", insertable = false, updatable = false)
    private Vegetable ptrVegetable;
}

@Entity
@DiscriminatorValue("FRUIT")
class FruitFood extends Food {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ptr_id", referencedColumnName = "id", insertable = false, updatable = false)
    private Fruit ptrFruit;
}

相关问题