gpt4 book ai didi

java - Hibernate 命名查询复制粘贴

转载 作者:行者123 更新时间:2023-11-29 03:58:19 24 4
gpt4 key购买 nike

在我的 .hbm.xml 中有两个查询。第一个检索表中的记录数:

<query name="Airframe.SearchCount"><![CDATA[
select
count(*)
from
AirframeBean as a inner join
a.manufacturer as m
where
m.name like :manufacturer and
a.description like :description and
((a.percentSize <= :sizeMax and
a.percentSize >= :sizeMin) or
a.percentSize is null) and
((a.wingSpanInches <= :spanMax and
a.wingSpanInches >= :spanMin) or
a.wingSpanInches is null) and
((a.recommendedAuwMinLbs <= :auwMax and
a.recommendedAuwMaxLbs >= :auwMin) or
a.recommendedAuwMaxLbs is null)
]]></query>

第二个使用偏移量和限制逐页获取数据:

<query name="Airframe.SearchData"><![CDATA[
select
a
from
AirframeBean as a inner join
a.manufacturer as m
where
m.name like :manufacturer and
a.description like :description and
((a.percentSize <= :sizeMax and
a.percentSize >= :sizeMin) or
a.percentSize is null) and
((a.wingSpanInches <= :spanMax and
a.wingSpanInches >= :spanMin) or
a.wingSpanInches is null) and
((a.recommendedAuwMinLbs <= :auwMax and
a.recommendedAuwMaxLbs >= :auwMin) or
a.recommendedAuwMaxLbs is null)
]]></query>

查询几乎相同。唯一的区别是第一个以 select count(*) 开头,第二个以 select a 开头。有没有办法避免复制粘贴?

更新主要问题是我需要 Hibernate 在启动时验证模式、映射和 HQL 查询。

最佳答案

你可以这样做:-

命名查询

#SELECTOR# 是您的 Java 代码必须替换的占位符。

<query name="Airframe"><![CDATA[
select
#SELECTOR#
from
AirframeBean as a inner join
a.manufacturer as m
where
m.name like :manufacturer and
a.description like :description and
((a.percentSize <= :sizeMax and
a.percentSize >= :sizeMin) or
a.percentSize is null) and
((a.wingSpanInches <= :spanMax and
a.wingSpanInches >= :spanMin) or
a.wingSpanInches is null) and
((a.recommendedAuwMinLbs <= :auwMax and
a.recommendedAuwMaxLbs >= :auwMin) or
a.recommendedAuwMaxLbs is null)
]]></query>

hibernate 代码

public Long searchCount() {
String sql = getQueryString("Airframe").replace("#SELECTOR#", "count(*)");
return (Long) session.createSQLQuery(sql, args...).uniqueResult();
}

@SuppressWarnings("unchecked")
public List<AirframeBean> getAirframeBeans() {
String sql = getQueryString("Airframe").replace("#SELECTOR#", "a");
return session.createSQLQuery(sql, args...).list();
}

private String getQueryString(String namedQuery) {
return session.getNamedQuery(namedQuery).getQueryString();
}

关于java - Hibernate 命名查询复制粘贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5050943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com