您好我正在尝试将基于旧的基于sql的查询框架迁移到基于Hibernate Criteria,目前我正在使用Hibernate 3.2版。和mysql v 5.0.54
我的问题是我想编写一个标准,返回不在一组包含的元素中具有值的所有Bean。
bean的hibernate配置文件摘要是:
<hibernate-mapping package="com.mydomain.beans">
<typedef class="com.mydomain.dao.util.HibernateAgentOptionType" name="agent-option"/>
<class name="Agent" table="agent">
...
<set name="agentOptions" table="agent_options" fetch="join" lazy="true">
<key column="agt_id"/>
<element column="identifier" type="agent-option"/>
</set>
</class>
</hibernate-mapping>
类文件类似于:
public class Agent {
...
public Set<Option> getAgentOptions() {
return agentOptions;
}
public void setAgentOptions(Set<Option> _agentOptions) {
this.agentOptions = _agentOptions;
}
public enum Option {
WEB_SITE_SYNDICATE ("web-site-syndicate"),
RECEIVE_PREMIUM_ENQUIRIES ("receive-premium-enquiries"),
DO_NOT_SYNDICATE_ADS_TO_THIRD_PARTIES ("do-not-syndicate-ads-to-third-parties")
}
}
我想在其agentOptions中检索没有选项“DO_NOT_SYNDICATE_ADS_TO_THIRD_PARTIES”的所有座席
我之前使用的sql类似于:
SELECT agt.id
FROM agent agt
WHERE agt.id NOT IN (
SELECT sub_agt.id FROM agent sub_agt
JOIN agent_options AS agt_options ON agt_options.agt_id = sub_agt.id
WHERE agt_options.identifier = 'do_not_syndicate_ads_to_third_parties'
)
我试过这个:
...
Criteria crit = getHibernateSession().createCriteria(Agent.class);
crit.addRestriction(Restriction.not(Restriction.in("agentOptions", noSyndicatedAds)));
...
哪个吐出坏sql
我也尝试使用别名:
...
crit.createAlias("agentOptions", "agentOption");
crit.add(Restrictions.not(Restrictions.in("agentOption", options)));
...
引发异常:
org.hibernate.MappingException:collection不是关联:Agent.agentOptions
最后我决定尝试一个粗暴的SQL标准:
...
crit.add(Restrictions.sqlRestriction(" {alias}.id not in " +
"(select agt_sub.id " +
"from agent agt_sub " +
"join agent_options as agent_options_sub on agent_options_sub.agt_id = agt_sub.id " +
"where agent_options_sub.identifier in (?)) ",
Agent.Option.DO_NOT_SYNDICATE_ADS_TO_THIRD_PARTIES.getIdentifier(),
new org.hibernate.type.StringType()
));
...
哪个有效,但看起来有点难看。
有没有人知道是否有办法使用std Criteria API而不必诉诸sql。
非常欢迎任何帮助或建议。即使他们需要升级到更新版本的Hibernate。
干杯 西蒙
答案 0 :(得分:0)
将子查询构建为DetachedCriteria
,然后使用嵌套的Restrictions
来获得NOT IN
。在你的情况下:
DetachedCriteria subquery = DetachedCriteria.forClass(Agent.class);
subquery.createAlias("agentOptions", "agentOption");
subbquery.add(Restrictions.eq("identifier", Agent.Option.DO_NOT_SYNDICATE_ADS_TO_THIRD_PARTIES.getIdentifier());
subquery.setProjection(Projections.property("agt_id")); // only return one field
crit.add(Restrictions.not(Restrictions.in("agt_id", subquery)));