Hibernate named query examples

来源:互联网 发布:更改mac屏幕下面的图标 编辑:程序博客网 时间:2024/05/20 20:20

Often times, developer like to put HQL string literals scatter all over the Java code, this method is hard to maintaine and look ugly. Fortunately, Hibernate come out a technique called “names queries” , it lets developer to put all HQL into the XML mapping file or via annotation.

How to declare named query

The named query is supported in both HQL or native SQL. see examples…

1. XML mapping file

HQL in mapping file

<!-- stock.hbm.xml --><hibernate-mapping>    <class name="com.mkyong.common.Stock" table="stock" ...>        <id name="stockId" type="java.lang.Integer">            <column name="STOCK_ID" />            <generator class="identity" />        </id>        <property name="stockCode" type="string">            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />        </property>        ...    </class>    <query name="findStockByStockCode">        <![CDATA[from Stock s where s.stockCode = :stockCode]]>    </query></hibernate-mapping>

Native SQL in mapping file

<!-- stock.hbm.xml --><hibernate-mapping>    <class name="com.mkyong.common.Stock" table="stock" ...>        <id name="stockId" type="java.lang.Integer">            <column name="STOCK_ID" />            <generator class="identity" />        </id>        <property name="stockCode" type="string">            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />        </property>        ...    </class>    <sql-query name="findStockByStockCodeNativeSQL">    <return alias="stock" class="com.mkyong.common.Stock"/>    <![CDATA[select * from stock s where s.stock_code = :stockCode]]>    </sql-query></hibernate-mapping>

You can place a named query inside ‘hibernate-mapping‘ element, but do not put before the ‘class‘ element, Hibernate will prompt invalid mapping file, all your named queries have to put after the ‘class‘ element.

Note
Regarding the CDATA , it’s always good practice to wrap your query text with CDATA, so that the XML parser will not prompt error for some special XML characters like ‘>’ , <‘ and etc.

2. Annotation

HQL in annotation

@NamedQueries({    @NamedQuery(    name = "findStockByStockCode",    query = "from Stock s where s.stockCode = :stockCode"    )})@Entity@Table(name = "stock", catalog = "mkyong")public class Stock implements java.io.Serializable {...

Native SQL in annotation

@NamedNativeQueries({    @NamedNativeQuery(    name = "findStockByStockCodeNativeSQL",    query = "select * from stock s where s.stock_code = :stockCode",        resultClass = Stock.class    )})@Entity@Table(name = "stock", catalog = "mkyong")public class Stock implements java.io.Serializable {...

In native SQL, you have to declare the ‘resultClass‘ to let Hibernate know what is the return type, failed to do it will caused the exception “org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported“.

Call a named query

In Hibernate, you can call the named query via getNamedQuery method.

Query query = session.getNamedQuery("findStockByStockCode").setString("stockCode", "7277");Query query = session.getNamedQuery("findStockByStockCodeNativeSQL").setString("stockCode", "7277");

Conclusion

Named queries are global access, which means the name of a query have to be unique in XML mapping files or annotations. In real environment, it’s always good practice to isolate all the named queries into their own file. In addition, named queries stored in the Hibernate mapping files or annotation are more easier to maintain than queries scattered through the Java code.

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 不小心踩到仓鼠吐血了怎么办 不小心踩到仓鼠的头怎么办 母仓鼠生完孩子特别暴躁怎么办 被仓鼠咬出血怎么办要不要打针 被小仓鼠咬出血了该怎么办 仓鼠咬破手指流血了该怎么办 小仓鼠的手被棉花丝绑住了怎么办 荷兰猪如果不小心撞流血了怎么办 帮同事刷杯子但把杯子弄坏了怎么办 贵宾犬喜欢张开嘴巴跟人玩怎么办 鼻烟放了几天感觉跟受潮一样怎么办 两个月宝宝鼻屎堵住鼻子怎么办 肉包着智齿怎么办洗燥电影完整版 大腿内侧突然长黑痣越来越大怎么办 肚脐发炎、不脱落怎么办_妈网百科 老公出轨找个按摩的还不离婚怎么办 别人拿错钥匙装修好了房子怎么办 撞车后对方全责却不赔钱怎么办 我的世界国服客户端都是英文怎么办 下载的3d模型没有材质怎么办 写字时习惯把本子放歪该怎么办 被蚊子咬后留下硬疙瘩怎么办 吃冰镇西瓜导致呼吸不顺怎么办 吃冰镇西瓜嚓气导致呼吸不顺怎么办 在pr里面找不到做字幕的怎么办 电脑主机电源坏了接口坏了怎么办 邻居捡到我手机不给这种情况怎么办 婆婆总在儿子面前说媳妇坏话怎么办 试管准备取卵雌激素低该怎么办 订了火车票了忘记带身份证怎么办 网上买火车票忘记带身份证了怎么办 网上买的火车票忘记带身份证怎么办 深圳东站不卖站台票要送客怎么办 网吧刷身份证机器突然不好使怎么办 买了个衣服穿起来有点老气怎么办 美股主动退市股票钱怎么办 新注册的微信号被实名认证了怎么办 他出轨对我冷暴力孩子小怎么办 给情人发红包被老婆发现了怎么办一 情人和我出轨被他老婆发现了怎么办 情人老婆再次发我的存在怎么办