【发布时间】:2022-09-27 18:35:44
【问题描述】:
我创建了抽象类实体(我想创建不同类型的形状):
@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();
}
}
现在对于控制器中的测试,我想创建新实体 - 在 cmets 中我将响应放在控制台中:
@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,我得到了空值。
标签: java spring hibernate relational-database one-to-one