如何在休眠模式下正确地一对一映射?

时间:2018-06-20 17:37:31

标签: hibernate spring-boot

我正在使用Spring Boot和Hibernate来制作REST API。基本上,它是目标跟踪应用程序,在其中我们有目标,达到目标的里程碑以及里程碑的固定状态数,例如“ COMPLETED”,“ IN_PROCESS”,“ AWAITING”。目前,我在加入状态和里程碑实体方面遇到问题。在测试过程中如何通过写入status_id来设置状态?

这里是 ER-diagram

里程碑模型

@Entity
@Table(name = "milestones")
@EntityListeners(AuditingEntityListener.class)
public class Milestone implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Size(max = 300)
private String milestoneDescription;

@NotBlank
@Size(max = 300)
private String measureDescription;


@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date dueDate;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "goal_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Goal goal;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "status_id")
private Status status;

//为简洁起见,省略了构造函数,getter和setter

状态模型

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(length = 60)
private String name;

@OneToOne(fetch = FetchType.LAZY,
        cascade =  CascadeType.ALL,
        mappedBy = "status")
private Milestone milestone;

里程碑控制器

@RestController
public class MilestoneController {

@Autowired
private MilestoneRepository milestoneRepository;

@Autowired
private GoalRepository goalRepository;

@Autowired
private StatusRepository statusRepository;


@GetMapping("/goals/{goalId}/milestones")
public Page<Milestone> getAllMilestonesByPostId(@PathVariable(value = "goalId") Long goalId,
                                              Pageable pageable) {
    return milestoneRepository.findByGoalId(goalId, pageable);
}

@PostMapping("/goals/{goalId}/milestones")
public Milestone createMilestone(@PathVariable (value = "goalId") Long goalId,
                             @Valid @RequestBody Milestone milestone) {
    return goalRepository.findById(goalId).map(goal -> {


//milestone.setStatus(statusRepository.findById(milestone.getStatus().getId()));
            milestone.setGoal(goal);
            return milestoneRepository.save(milestone);
        }).orElseThrow(() -> new ResourceNotFoundException("Goal","id", goalId));
    }

Here,邮递员测试说状态为空,但应该是状态名称

0 个答案:

没有答案