实体调查:
@Entity
@Table(name = "Survey")
public class Survey implements Serializable {
private Long id;
private String name;
private String address;
private List<Question> questions;
@Id
@Column(name = "id")
public Long getId() {
return id;
}
@Column(name = "name")
public String getName() {
return name;
}
@Column(name = "address")
public String getAddress() {
return address;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "survey")
public List<Question> getQuestions() {
return questions;
}
public void setId(Long id) {
this.id = id;
}
public void setName(final String name) {
this.name = name;
}
public void setAddress(final String address) {
this.address = address;
}
public void setQuestions(List<Question> _questions) {
this.questions = _questions;
}
}
问题实体:
@Entity
@Table(name = "Question")
public class Question {
private Long id;
private String question;
private Survey survey;
@Id
@Column(name = "id")
public Long getId() {
return id;
}
@Column(name = "question")
public String getQuestion() {
return question;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "survey_id")
public Survey getSurvey() {
return survey;
}
public void setId(Long id) {
this.id = id;
}
public void setQuestion(String question) {
this.question = question;
}
public void setSurvey(Survey survey) {
this.survey = survey;
}
}
问题Crud回购:
public interface QuestionRepo extends CrudRepository<Question, Long> {
}
控制器:
@RestController
@RequestMapping("/default")
public class DefaultEndpoint {
@Autowired
private QuestionRepo questionRepo;
@PostMapping(value = "/saveQuestion")
public void saveQuestion(@Param("id") Long id, @Param("question") String question, @Param("survey_id") Long survey_id) {
Question questionObject = new Question();
questionObject.setId(id);
questionObject.setQuestion(question);
Survey survey = surveyRepo.findById(survey_id).get();
survey.setName("example");
questionObject.setSurvey(survey);
questionRepo.save(questionObject);
}
}
在控制器代码段中,当我做 Survey.setName(“ example”); 。此更改反映在数据库上。
这意味着,即使未指定级联类型,使用EntityManager方法MERGE和PERIST实现的save()操作也会级联到子实体。 这是应该如何工作的,还是我在犯一些愚蠢的错误? 非常感谢 !
问题来源:Stack Overflow
请检查@ManyToOne注释以查看默认级联为“ none”。
public @interface ManyToOne {
/**
* (Optional) The operations that must be cascaded to
* the target of the association.
*
* <p> By default no operations are cascaded.
*/
CascadeType[] cascade() default {};
}
没有级联发生。
您观察到的效果很可能是以下两个功能的组合:
如果您正在运行Web应用程序,则Spring Boot默认情况下会注册OpenEntityManagerInViewInterceptor以应用“在视图中打开EntityManager”模式,以允许在Web视图中进行延迟加载。如果您不希望出现这种情况,则应spring.jpa.open-in-view在application.properties 中将其设置为false。
脏检查是众所周知的,但是对于某些开发人员而言,View Open Session往往会感到惊讶(例如,在Spring中看到另一个相关效果-同一实体在@EventListener上分离但在@Service类中附加)
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。