Как предложил @Karol Dowbecki,
преобразует объект JSON в DTO и использует этот DTO для получения User
, Tag
сущностей из соответствующих репозиториев .
Наконец, создайте объект сущности Вопрос и сохраните его.
Сущность Вопроса
@Entity
@Table(name = "question")
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title")
private String title;
@Column(name = "body")
private String body;
@Temporal(TemporalType.DATE)
@Column(name = "date_created")
private Date dateCreated;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "tag_id")
private Set<Tag> tag;
@Column(name = "answer_count")
private int answerCount;
@Column(name = "view_count")
private int viewCount;
}
Сущность пользователя
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
Tag Entity
@Entity
@Table(name = "tag")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "username")
private String username;
@Temporal(TemporalType.DATE)
@Column(name = "date_created")
private Date dateCreated;
}
Класс DTO
public class QuestionDTO {
private Long id;
private String title;
private String body;
private Date dateCreated;
private Long user;
private Long tag;
private int answerCount;
private int viewCount;
}
Тестовый класс
@Service
public class TestService {
@Autowired
private QuestionRepository questionRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private TagRepository tagRepository;
public void addQuestion(QuestionDTO dto) {
Tag tag = null;
User user = null;
Question question = null;
Set<Tag> tags = null;
tag = tagRepository.findById(dto.getTag());
tags = new HashSet<>();
tags.add(tag);
user = userRepository.findById(dto.getUser());
question = new Question();
question.setTag(tags);
question.setUser(user);
question.setId(dto.getId());
question.setBody(dto.getBody());
question.setTitle(dto.getTitle());
question.setViewCount(dto.getViewCount());
question.setAnswerCount(dto.getAnswerCount());
question.setDateCreated(dto.getDateCreated());
questionRepository.save(question);
}
}
ПРИМЕЧАНИЕ : Соотношение между Question
и Tag
в OneToMany
, вы должны использовать тип Collection
.