hibernate 在具有继承的实体中设置一对一关系

mbyulnm0  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(160)

我创建了抽象类实体(我想创建不同类型的形状):

@Entity
@Inheritance(strategy = TABLE_PER_CLASS)
@Getter
@Setter
@NoArgsConstructor
public abstract class ShapeEntity {
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
    @OneToOne
    private ShapeDetailsEntity shapeDetailsEntity;

    public abstract double getArea();

    public abstract double getPerimeter();
}

我想要每次添加到每个实体表中都有详细信息:

@Entity
@Getter
@Setter
@Table(name = "shape_details")
@AllArgsConstructor
public class ShapeDetailsEntity {
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
    ...
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "shapeDetailsEntity", fetch = FetchType.LAZY)
    private ShapeEntity shapeEntity;

创建实体的逻辑正在使用中:

public class ShapeService {
    public ShapeEntity createShape(ShapeType type, List<Double> parameters) {
        switch (type) {
            case CIRCLE:
                return circleEntityRepository.saveAndFlush(new CircleEntity(parameters));
            case SQUARE:
                return squareEntityRepository.saveAndFlush(new SquareEntity(parameters));
            case RECTANGLE:
                return rectangleEntityRepository.saveAndFlush(new RectangleEntity(parameters));
            default:
                throw new IllegalArgumentException();
        }
    }

现在,对于控制器中的测试,我想创建新的实体-在注解中,我将响应放在控制台中:

@PostMapping
public ResponseEntity<String> post(@Valid @RequestBody ShapeRequestModel shapeRequestModel) {
    ShapeEntity shapeEntity = shapeService.createShape(ShapeType.valueOf(shapeRequestModel.getType()), shapeRequestModel.getParameters());
    ShapeDetailsEntity shapeDetailsEntity = shapeService.createShapeDetails(shapeEntity);
    System.out.println(shapeDetailsEntity.getShapeEntity().toString()); // -> CircleEntity{radius=4.5}
    System.out.println(shapeDetailsEntity); // -> ShapeDetailsEntity{all details...}
    System.out.println(shapeEntity.getShapeDetailsEntity().toString()); // -> java.lang.NullPointerException: null

    return new ResponseEntity<>(shapeEntity.toString(), HttpStatus.CREATED);
}

在**shapeService.createShapeDetails(shapeEntity)**中,如下所示:

public ShapeDetailsEntity createShapeDetails(ShapeEntity shapeEntity) {
    ShapeDetailsEntity shapeDetailsEntity = new ShapeDetailsEntity();
    shapeDetailsEntity.setShapeEntity(shapeEntity);
    return shapeDetailsEntityRepository.saveAndFlush(shapeDetailsEntity);
}

我应该如何正确地做才不会在**shapeEntity.getShapeDetailsEntity().toString())**中得到空值?在数据库中,当应该是shapeDetailsEntity的id时,我得到了空。

nkoocmlb

nkoocmlb1#

您正在创建的ShapeEntity没有分配ShapeDetailsEntity,即该字段为空,这就是您获得NPE的原因。如果您不想这样做,则必须为该字段分配一个对象。
我想,这个shapeService.createShapeDetails(shapeEntity);代码应该不是必需的。您的ShapeService.createShape方法应该为该字段分配一个ShapeDetailsEntity对象。

相关问题