也许是一个微不足道的问题,但我查遍了所有能找到的方法,但找不到解决方案
我试图使用post请求保存一个新的GeologicalClass(不是最好的命名,但这就是任务),但是将其保存到数据库时,依赖字段section_id被写入为null
这是我的代码:
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "sections")
public class Section {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", nullable = false)
private String name;
private boolean isDeleted;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "section")
private List<GeologicalClass> geologicalClasses;
}
@AllArgsConstructor
@NoArgsConstructor
@Getter@Setter
@Entity
@ToString(exclude = "section")
@Table(name = "geological_classes")
public class GeologicalClass {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "bigint")
private Long id;
private String name;
private String code;
private boolean isDeleted;
@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(
name = "section_id",
insertable = false,
nullable = false)
private Section section;
}
@Service
public class GeologicalClassServiceImpl implements GeologicalClassService {
@Override
public GeologicalClass createGeologicalClass(GeologicalClass geologicalClass) {
return geologicalClassRepository.save(geologicalClass);
}
}
@RestController
@RequestMapping("/api/geological-classes")
@RequiredArgsConstructor
public class GeologicalClassController {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public RestResponse createGeologicalClass(@RequestBody GeologicalClass geologicalClass) {
GeologicalClass createdGeologicalClass = geologicalClassService.createGeologicalClass(geologicalClass);
return new RestResponse(createdGeologicalClass);
}
}
我建议使用序列来生成 ID。以下是如何将其应用于 JPA 中的 @ID 字段的示例:
@Getter
@Setter
@Table(name = "table")
@SequenceGenerator(
name = "table_id_seq",
sequenceName = "table_id_seq",
allocationSize = 1)
public class Table {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "table_id_seq")
private Long id;
}