to BinnyJ:
>1.Question父类和 多项选择题目,单项选择题目 ,判断题目子类的继承关系 ,如何映射到关系数据库中。我的初步想法是关系数据库建立两个表 tbl_question, tbl_selectOption
不要去想建什么数据库表,那是hibernate会为你完成的事(跑一下schema export——也叫hbm2ddl——就搞定了。这不是关键,关键在于你根本不用关心生成的db schema是什么样的)。从现在开始,你的思维里应该只有对象!
这几个对象间的关系比方说就是这样:
多项选择题目 extends Question
单项选择题目 extends Question
那么OR mapping可以是这样:
@javax.persistence.Entity
@javax.persistence.Inheritance(strategy = JOINED)
class Question {...}
其中strategy属性可以指定如下值:
* javax.persistence.InheritanceType.SINGLE_TABLE
每个class hierarchy一张表,就是所有继承自同一个父类的都保存在一张表里,其结果和你上面说的情况类似,不同的是,你不用手动定义一个questionType,也不用为每个对象维护这样一个属性的值,hibernate会为你解决。
See Also: @javax.persistence.DiscriminatorValue
* javax.persistence.InheritanceType.JOINED
A strategy in which fields that are specific to a subclass are mapped to a separate table than the fields that are common to the parent class, and a join is performed to instantiate the subclass.
* javax.persistence.InheritanceType.TABLE_PER_CLASS
A table per concrete entity class
@Entity
class 多项选择题目 extends Question {...}
@Entity
class 单项选择题目 extends Question {...}
查询(以下例子使用JPQL. hibernate完全支持JPQL. 可以说HQL是JPQL的超集):
比如查询所有的 SingleSelectQuestion(单项选择题目):
select q from 单项选择题目 as q
如此即可!千万不要把JPQL(hql)当sql写、当sql理解
> 难道Hibernate能在xml configuration加入查询条件?
确实如此,比如OneToMany,ManyToMany等映射,都可以设置where字句的;还有一些其他的情况,也可以设置查询条件字句,详见hibernate文档。而你这里的继承关系,并不需要通过这样的方式来查询。
关于你提的第二个问题,要看用户的具体需求了。