【发布时间】:2020-07-31 12:26:45
【问题描述】:
假设我有三个实体。
@Entity
public class Process {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String name;
@ManyToAny(
metaColumn = @Column(name = "node_type"),
fetch = FetchType.LAZY
)
@AnyMetaDef(
idType = "long", metaType = "string",
metaValues = {
@MetaValue(targetEntity = Milestone.class, value = MILESTONE_DISC),
@MetaValue(targetEntity = Phase.class, value = PHASE_DISC)
}
)
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@JoinTable(
name = "process_nodes",
joinColumns = @JoinColumn(name = "process_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "node_id", nullable = false)
)
private Collection<ProcessNode> nodes = new ArrayList<>();
...
}
@Entity
@ToString
@DiscriminatorValue(MILESTONE_DISC)
public class Milestone implements ProcessNode {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<ResultDefinition> results;
@ManyToOne()
private Process process;
...
}
@Entity
@ToString
public class ResultDefinition {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String externalId;
private String name;
private ResultType resultType;
}
我想从我的客户那里将 ResultDefinition 类型的对象添加到进程中的里程碑,如下所示:
@Transactional
@PostMapping("/{milestone_id}/results")
public ResultDefinitionDto createResult(@PathVariable("milestone_id") Long milestoneId, @RequestBody ResultDefinitionDto dto) {
Process foundProcess = getProcess(milestoneId);
checkFoundProcess(milestoneId, foundProcess);
Milestone milestone = getMilestone(foundProcess, milestoneId);
ResultDefinition resultDefinition = resultDefinitionMapper.fromDTO(dto);
milestone.addResult(resultDefinition);
processService.save(foundProcess);
//TODO: Find out why this is necessary (???)
ResultDefinition savedResult = milestone.getResult(resultDefinition.getName());
return resultDefinitionMapper.fromEntity(savedResult);
}
在我的方法 createResult 中,我将 resultDefinition 添加到里程碑结果集合中。 当我保存父 foundProcess 时,我看到 foundprocess->milestone->resultDefinition 得到了持久化并获得了一个 ID。当我调用 resultDefinition.getId() 它返回 null。 foundProcess 中的 ResultDefinition 对象也是另一个引用,与我添加到milestone.results 中的不同。
为什么我在调用milestone.getResult() 时会得到正确的实例?
编辑:我的 processService / repository 的实现
@Override
public Process save(Process entity) {
return processRepository.saveAndFlush(entity);
}
public interface ProcessRepository extends JpaRepository<Process, Long>, JpaSpecificationExecutor<Process> {
...
}
【问题讨论】:
标签: java hibernate spring-data-jpa