【发布时间】:2015-06-28 03:52:06
【问题描述】:
由于某种原因,我无法让 Hibernate Inheritance strategy=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;
}
@实体
public class Exam {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer examid;
private String examName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "exam")
private Set<ExamObject> object
}
我的 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() 时,我总是得到空值。我怎样才能让它工作?
【问题讨论】:
-
这是意料之中的:您的代码从未将任何内容分配给
exam.object,因此它为空。exam2和exam都指向同一个对象。 -
我已经用 onetoMany 映射了exam.object。所以我希望它在我检索考试时为我提供考试的考试对象列表。
-
您在一个事务中完成所有操作。因此,您坚持的考试按原样存储在第一级(会话)缓存中。当您执行查询时,Hibernate 会返回缓存中已经存在的相同实例。保持对象图的一致性是您的责任:如果您设置了一个问题的考试,那么这个问题应该添加到考试的对象中。
标签: spring hibernate spring-boot spring-data spring-data-jpa