出于某些原因,我无法获得Hibernate继承策略= InheritanceType.JOINED&的组合。 onetoMany工作。以下是实体。
@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 Boot启动课程
@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()
时,我总是会得到null。我怎样才能让它发挥作用?
答案 0 :(得分:1)
正如原始问题中的注释所解释的那样,问题是对象图未得到正确维护。以下函数的一行额外代码修复了该问题。已添加exam.setObjects(examQuestions);
@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);
exam.setObjects(examQuestions);
Iterable<Exam> examGet = examRepository.findAll();
for (Exam exam2: examGet) {
System.out.println("Exam question is .. " +exam2.getObjects());
}
}
答案 1 :(得分:0)
可能是问题
@OneToMany(fetch = FetchType.LAZY,mappedBy =“考试”) 私人设置对象
当您通过LAZY加载FetchType.LAZY
获取任何内容时。这将从父表中获取所有对象,即在此处检查,但不会在子/依赖表中查询数据。
例如,它不会点击ExamObject来获取它的数据,它只是用代理对象替换它。因此,如果你查询这个对象,那么你得到null作为结果。
使用FetchType.EAGER