Вот мой ответ и вопрос модель:
Код: Выделить всё
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Answer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int answerId;
private String answer;
private String status;
@ManyToOne()
@JoinColumn(name = "questionId", nullable = false)
private Question question;
}
Код: Выделить всё
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int questionId;
private String question;
private String questionType;
private String status;
@ManyToMany(mappedBy = "questions", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
private Set quizzes;
@OneToMany(mappedBy = "question",cascade = CascadeType.ALL, orphanRemoval = true)
private Set answers;
}
Код: Выделить всё
public class AnswerDTO {
@NotEmpty
private String answer;
@NotEmpty
private String status;
@NotNull
private Integer questionId;
}
Код: Выделить всё
@Configuration
public class Config {
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
// ignore null attributes on the source object on copying
modelMapper.getConfiguration()
.setSkipNullEnabled(true);
return modelMapper;
}
}
Код: Выделить всё
@Component
@AllArgsConstructor
public class AnswerBuilder {
private final ModelMapper modelMapper;
public Answer build(AnswerDTO dto) {
Answer model = modelMapper.map(dto, Answer.class);
return model;
}
public Optional build(Answer domain) {
AnswerDTO dto = modelMapper.map(domain, AnswerDTO.class);
return Optional.of(dto);
}
public Answer build(AnswerDTO dto, Answer domain) {
modelMapper.map(dto, domain);
return domain;
}
}
Код: Выделить всё
public int createNewAnswer(AnswerDTO dto) {
return Stream.of(dto)
.map(answerBuilder::build)
.map(answerRepository::save)
.map(Answer::getAnswerId)
.findFirst()
.get();
}
Код: Выделить всё
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'question_id', table 'SPRINGTEST.dbo.answer'; column does not allow nulls.
Подробнее здесь: https://stackoverflow.com/questions/790 ... repository