public void testNamedQuery(){ Session session = HibernateUtil.getInstance().getSession(); //HQL解析成SQL是非常耗费资源的,假如你的HQL被访问了上千万次. //可以在xxx.hbm.xml中定义该HQL, hibernate 在启动时就会去解析它,之后用到就不用再解析了. for(int i=0; i<1000; i++){ session.getNamedQuery("SELECT_ALL_EMPLOYEE") .setParameter("name", "jack") .list(); } session.close(); }
xxx.hbm.xml 文件配置示例如下:
<hibernate-mapping package="cd.itcast.day4.extend"> <!-- per table --> <class name="Product" table="product"> <id name="id" column="id"> <generator class="org.hibernate.id.enhanced.TableGenerator"> <param name="segment_value">IdDomain</param> <param name="initial_value">1</param> <param name="increment_size">1</param> </generator> </id> <property name="name" column="name"/> <property name="price" column="price"/> <union-subclass name="BookProduct" table="book_product"> <property name="isbn" column="isbn"/> </union-subclass> <union-subclass name="WearProduct" table="wear_product"> <property name="color" column="color"/> </union-subclass> </class> <query name="SELECT_ALL_EMPLOYEE"> <![CDATA[FROM Employee e WHERE e.name = :name]]> </query> </hibernate-mapping>
其中 <![CDATA[...]]> 是为了防止HQL 语句中包含关键字, 如果没有,可以不用.
hibernate_namedQuery, HQL解析优化
最新推荐文章于 2020-03-13 13:38:17 发布