I want to create a many to many relationship with a extra column. I configured this:
@Entity
public class Configuration extends AbstractEntity {
@OneToMany(
mappedBy = "configuration",
cascade=CascadeType.ALL,
orphanRemoval = true
)
@JsonIgnore
private List<ConfigurationQuestion> configurationQuestions = new ArrayList<>();
public void addQuestion(QuestionDTO question) {
ConfigurationQuestion configurationQuestion = new ConfigurationQuestion(this,
question.getQuestion(), question.getResponse());
configurationQuestions.add(configurationQuestion);
}
}
Join table
@Entity
public class ConfigurationQuestion implements Serializable {
@EmbeddedId
private ConfigurationQuestionId id ;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("configurationId")
private Configuration configuration;
@ManyToOne(fetch = FetchType.EAGER)
@MapsId("questionId")
@JoinColumn(name="question_id")
private Question question;
private Integer response;
public ConfigurationQuestion(Configuration configuration, Question question,
Integer response) {
this.configuration = configuration;
this.question = question;
this.response = response;
this.id = new ConfigurationQuestionId(configuration.getId(), question.getId());
}
}
Embedable id
@Embeddable
public class ConfigurationQuestionId implements Serializable {
private Long configurationId;
private Long questionId;
}
In question I don't have any mapping I want to do it one directional. My problem is when I try to save something like this. I want to save a configuration that have as question just ids not the entire object, it is saved separatly.
In Question entity I don't have any mapping I want to do it one directional. My problem is when I try to save something like this. I want to save a configuration that has as question/questions just ids not the entire objects, it is saved separately.
Configuration configuration = new Configuration();
Question question = new Question();
question.setId(1L);
configuration.addQuestion(new QuestionDTO(question, 1));
repository.save(configuration);
I receive the following error. I don't want to cascade the changes to Question entity, if I remove Cascade.ALL from Configuration isn't inserting anything in the join table. Can I do this without making a find for questions?
detached entity passed to persist: Question