По какой-то причине я не могу получить комбинацию стратегии Hibernate Inheritance = InheritanceType.JOINED & onetoMany working. Ниже приведены сущности.Стратегия наследования Hibernate = InheritanceType.JOINED & onetoMany с spring-data-jpa
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="OBJECT_TYPE")
public abstract class ExamObject {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "examid", nullable = false)
private Exam exam;
}
@Entity
@DiscriminatorValue("Q")
public class ExamQuestion extends ExamObject{
private Integer questionNumber;
private String questionDesc;
}
@Entity
public class Exam {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer examid;
private String examName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "exam")
private Set<ExamObject> object
}
My Spring Загрузочный запустить класс
@SpringBootApplication
public class ExamApp implements CommandLineRunner {
@Autowired
private ExamQuestionRepository examQuestionRepository;
@Autowired
private ExamRepository examRepository;
public static void main(String[] args) {
SpringApplication.run(ExamApp.class, args);
}
@Override
@Transactional
public void run(String... arg0) throws Exception {
Exam exam = new Exam();
exam.setExamName("Exam1");
examRepository.save(exam);
String[] questions = new String[]{"Question1,Question2"};
ArrayList<ExamQuestion> examQuestions = new ArrayList<ExamQuestion();
int index = 0;
for(String questionNoDesc: questions){
index++;
ExamQuestion examQuestion = new ExamQuestion();
examQuestion.setQuestionDesc(questionNoDesc);
examQuestion.setQuestionNumber(index);
examQuestion.setExam(exam);
examQuestions.add(examQuestion);
}
examQuestionRepository.save(examQuestions);
Iterable<Exam> examGet = examRepository.findAll();
for (Exam exam2: examGet) {
System.out.println("Exam question is .. " +exam2.getObjects());
}
}
}
проблем заключается в том, что всякий раз, когда я печатаю "Exam question is .. "+exam2.getObjects()
, я всегда получаю нулевой. Как я могу заставить это работать?
Ожидается: ваш код никогда не присваивает что-либо 'exam.object', поэтому он равен нулю. 'exam2' и' exam' оба указывают на тот же самый объект. –
Я сопоставил exam.object с onetoMany. Поэтому я ожидаю, что он предоставит мне список экзаменационных экзаменов, когда я получу экзамен. – ArunM
Вы делаете все в одной транзакции. Таким образом, экзамен, который вы сохраняете, сохраняется как в кеше первого уровня (сеанса). Когда вы выполняете запрос, Hibernate возвращает этот же экземпляр уже в кеш. Вы несете ответственность за поддержание согласованности графа объектов: если вы задали вопрос на экзамене, то этот вопрос должен быть добавлен к объектам экзамена. –