我有以下設定:
- 微創 3.x
- 爪哇 15
我正在嘗試更新的物體:
@Setter
@Getter
@Entity
@ToString
@Table(name = "single_choice_question")
public class SingleChoiceQuestion extends OrderedQuestion {
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
private SingleAnswer answer;
@Override
public void answer(Answer answer) {
if (answer instanceof SingleAnswer single) {
this.answer = single;
}
throw new IllegalArgumentException("answer is not of SingleAnswer type");
}
}
它的子物體我試圖作為上述物體的一部分堅持下去:
@Getter
@Setter
@Entity
@Table(name = "single_answer")
public class SingleAnswer extends Answer {
@OneToOne private AnswerOption choice;
}
所有物體都繼承自:
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
@Column(updatable = false, nullable = false, length = 36)
@Type(type = "pkg.UuidUserType") // Maps UUID to SQL VARCHAR.
private UUID id;
@Version
@Column(nullable = false)
private Integer version;
...
}
基本答案類:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Answer extends BaseEntity {
@Column(nullable = false)
private Boolean correct;
}
執行以下幾行:
@ReadOnly
public class MyService {
@Transactional
public <A extends AnswerDto> A answer(A dto, UUID question) {
var answer = questionsMapper.toAnswer(dto);
answer.setCorrect(isCorrect(dto, question));
var orderedQuestion =
orderedQuestionRepository
.findById(question)
.orElseThrow(() -> new NotFoundException("question", question));
orderedQuestion.answer(answer, false);
orderedQuestionRepository.saveAndFlush(orderedQuestion);
return dto;
}
}
預期行為:SingleAnswer 實體被持久化,其 FK 保存在answer_id問題的列中。
實際行為:SingleAnswer 實體被持久化,但它的 FK 沒有保存在answer_id問題的列中。它們沒有以任何方式連接,因此孤兒移除似乎也不起作用。
在檢查了 hibernate 的日志后,我可以看到它只執行insert并且不執行 和update問題。
Another observation is when I remove flushing, orphan removal does work - SingleAnswer doesn't persist, although the FK situation isn't resolved still.
orderedQuestion.answer(answer);
orderedQuestionRepository.save(orderedQuestion);
I can't see anything wrong with this very basic setup, any help would be appreciated.
uj5u.com熱心網友回復:
@JoinColumn在SingleChoiceQuestion物體中包含指示外鍵的注釋:
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "answer_id")
private SingleAnswer answer;
uj5u.com熱心網友回復:
這個問題非常簡單,@ReadOnly有人在某個時候偷偷溜進了班級,我沒有注意到
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/351328.html
標籤:java hibernate one-to-one micronaut micronaut-data
