对于Hibernate不熟练的使用者,不要滥用关联关系,里面有太多你无法控制的东西。 最好老老实实地跟表字段建一样的属性。比如Tag定义一个字段tagclassid,存放TagClass的ID值而不是对象。public List<Article> findArticleByTagClass(TagClass tagClass); 实现这个方法的时候可以这样: select a from Article a,TagClass tc,Tag t where t.tagclassid=tc.id and tc.id=:tagclass.id
sorry,写错了。 我不对你用relationship mapping发表意见。我只说说如果我会怎么做。 表: article(id) tag(id,tagclassid) tagclass(id) 再加一个表述article与tag的关系表:articetag(articleid,tagid)做4个POJO,对应4个表 select a from Article a,TagClass tc,Tag t,ArticlTag at where at.articleid=a.id and at.tagid=t.id and t.tagclassid=tc.id and tc.id=:tagclass.id你可能认为写这个HQL麻烦, 不过我要告诉你,你用这点麻烦换取了更大灵活性和更好的控制性,是非常值得的。
最好老老实实地跟表字段建一样的属性。比如Tag定义一个字段tagclassid,存放TagClass的ID值而不是对象。public List<Article> findArticleByTagClass(TagClass tagClass);
实现这个方法的时候可以这样:
select a from Article a,TagClass tc,Tag t where t.tagclassid=tc.id and
tc.id=:tagclass.id
Criteria criteria = this.getSession().createCriteria(Article.class)
.createAlias("tags","t")
.add(Expression.eq("t.tagClass",tagClass));
return criteria.list();用hibernate时,老感觉以前那种用直接用sql的思维改不过来,只要换一下思维,用面对对象的方式去思考,才能真正体会到hibernate的好处。
我不对你用relationship mapping发表意见。我只说说如果我会怎么做。
表:
article(id)
tag(id,tagclassid)
tagclass(id)
再加一个表述article与tag的关系表:articetag(articleid,tagid)做4个POJO,对应4个表
select a from Article a,TagClass tc,Tag t,ArticlTag at
where
at.articleid=a.id and at.tagid=t.id and
t.tagclassid=tc.id and
tc.id=:tagclass.id你可能认为写这个HQL麻烦,
不过我要告诉你,你用这点麻烦换取了更大灵活性和更好的控制性,是非常值得的。
.createAlias("tags","t")
.add(Expression.eq("t.tagClass",tagClass));
return criteria.list();请搂主帮忙解释下,
createAlias("tags","t")
Expression.eq("t.tagClass",tagClass)
怎么理解阿,尤其是t.tagClass
t值得就是那个set是吗?可是这个set怎么有了tagClass属性了?请帮忙,我这块实在理解不了
这里的t是set中一个个具体的tag的代称。所以有tagClass属性了。
如果我要解除Article和Tag之间的关联,是否非得加载Article的tags Set,然后从Set中remove,然后再update?
有没有办法直接将而者关联表中的字段删除,而不用加载。hql怎么写?
======
答案:不用这么麻烦。简单点,就用Native SQL,自己写个SQL,想怎么删就怎么删!Hibernate就是个工具而已,不要被一个工具束缚了自己的思想!
晕死啊,看了好久,什么都没搞出来
谢谢hbwhwang的经验之谈