我有个表用来存储论坛的Topic活Reply,结构如下:
@Entity
@Table(name = "TopicOrReply")
public class TopicOrReply implements Serializable{
private Long id;
private String title;//标题,如果为空,那么表示“回复”。
private TopicOrReply repliedTopic;//指向该回复对应的topic
...
}
现在我想查询topic id是1以及其所有回复的记录集合。
我的做法:
Criteria criteria = ((org.hibernate.Session) em.getDelegate()).createCriteria(TopicOrReply.class);
Criterion criterion4Topic = Restrictions.and(
Restrictions.eq("id",this.getTopicId()),
Restrictions.eq("randomCode",this.getRandomCode())
);
Criteria subCriteria = criteria.createCriteria("repliedTopic");
subCriteria.add(criterion4Topic);
但是这样的查询,只能查询出某topic的所有回复,不包括该topic自身。
因为topic和reply的内容没什么区别【前者多一个title而已】,因此采用了一张表“TopicOrReply”。
请问如何把Topic一起查询出来?
请问如何把Topic一起查询出来?
请问如何把Topic一起查询出来?
[b]问题补充:[/b]
还是这里反映快,hibernate.org里面现在基本没有人回答问题了。
2008-05-28 jasongreen (初级程序员)
Criterion criterion4Topic = Restrictions.or(
Restrictions.and(
Restrictions.eq("id",this.getTopicId()),
Restrictions.eq("randomCode",this.getRandomCode())
),
Restrictions.eq("repliedTopic.id",this.getTopicId())
)
~~~~等我验证下。
2008-05-28 jasongreen (初级程序员)
select topic,relies from TopicOrReplies as relies join relies.repliedTopic as topic where topic.id=?
这样可以使topic,replies分离,在程序中比较好控制。也可以对replies进行想要的排序
~~~~~~~~因为我采用的是Seam方案,而且我需要利用
ScrollableResults cursor = this.getHibernateCriteriaWithoutOrderBy().scroll();
cursor.last();
this.totalRecords = cursor.getRowNumber() + 1;//行编号是从0开始的
cursor.close();
这种模式首先查出记录总数!然后计算分页信息。最后根据药抓取的第N页数据是否存在来决定是否去DB抓取数据。
1.我只想知道记录总数,不想抓取所有记录。
2.我只想抓取第N页的数据。
你这个方法是避开了Criterion的用法,我也考虑过。
但是目前用Criterion对于翻页来的性能来说,非常重要。Query要想计算总记录数还要用count,而用count又不能用order by,很烦的!所以被我废弃了。
[b]问题补充:[/b]
Criterion criterion4Topic = Restrictions.or(
Restrictions.and(
Restrictions.eq("id",this.getTopicId()),
Restrictions.eq("randomCode",this.getRandomCode())
),
Restrictions.eq("repliedTopic.id",this.getTopicId())
)
OK!~~~~多谢!!!
但是我依旧不明白一点:
这是我按照兄弟的回答进行改造过的能够运行的代码:
Criterion criterion4Topic = Restrictions.or(
Restrictions.and(
Restrictions.eq("id",this.getTopicId()),
Restrictions.eq("randomCode",this.getRandomCode())
),
Restrictions.eq("repliedTopic.id",this.getTopicId())
);
criteria.add(criterion4Topic);
而原来的代码就多了一句话,为什么就不能执行了呢?
不能运行的代码如下:
Criterion criterion4Topic = Restrictions.or(
Restrictions.and(
Restrictions.eq("id",this.getTopicId()),
Restrictions.eq("randomCode",this.getRandomCode())
),
Restrictions.and(
Restrictions.eq("repliedTopic.id",this.getTopicId()),
Restrictions.eq("repliedTopic.randomCode",this.getRandomCode())
)
);
criteria.add(criterion4Topic);
请兄弟指教。马上给分。