我想用一个额外的列创建一个多对多的关系。我配置了这个:
@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);
}
}
连接表
@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());
}
}
可嵌入的id
@Embeddable
public class ConfigurationQuestionId implements Serializable {
private Long configurationId;
private Long questionId;
}
在这个问题上,我没有任何映射,我想做单向映射。我的问题是当我试图保存像这样的东西时。我想保存一个只有it而不是整个对象的配置,它是单独保存的。
在有问题的实体中,我没有任何映射,我想做单向映射。我的问题是当我试图保存像这样的东西时。我想要保存一个配置,它只有it而不是整个对象,它是单独保存的。
Configuration configuration = new Configuration();
Question question = new Question();
question.setId(1L);
configuration.addQuestion(new QuestionDTO(question, 1));
repository.save(configuration);
我收到以下错误。我不想将更改级联到table,如果我从配置中删除Cascade.ALL,则不会在连接表中插入任何内容。我可以在不查找问题的情况下做到这一点吗?
detached entity passed to persist: Question
发布于 2018-10-30 16:53:07
如果您不想将更改从Configuration
实体Cascade
到Question
实体,则必须单独保存它。JPA提供者抱怨传递的实体仍然是分离的,这是正确的。它仍然只是一个普通的java对象实例,JPA EntityManager
并不知道它。
在保存Configuration
实体之前,请先尝试单独保存Question
。
如果数据库中已经有了Question
,知道它的ID,但又不想完整地获取它,那么可以使用getReference()
方法,该方法返回Entity
的代理。JPA提供者仍然需要一些开销来验证实例是否存在(如果实例不存在,它应该抛出一个EntityNotFoundException
),但是应该更加轻量级。
如果您使用的是Spring Data JpaRepository
,那么有一个类似的方法,它的名字很别扭,叫做getOne()
,它做的基本上是相同的事情(它称为EntityManager.getReference()
)。
https://stackoverflow.com/questions/53068754
复制相似问题