关闭

hibernate实现NULLS LAST

标签: hibernate
1376人阅读 评论(0) 收藏 举报
分类:

关于 hibernate 查询中实现order by的 NULLS LAST 和 NULLS FIRST

 1:创建一个CustomNullsFirstInterceptor类
 

package com.jnpm.util;

import org.apache.tools.ant.util.StringUtils;
import org.hibernate.EmptyInterceptor;

import com.sun.org.apache.commons.logging.Log;
import com.sun.org.apache.commons.logging.LogFactory;

public class MyNullsFirstInterceptor extends EmptyInterceptor {

    private static final long serialVersionUID = 1L;

        private final Log logger = LogFactory.getLog(getClass());  

        private static final String ORDER_BY_TOKEN = "order by";

        public String onPrepareStatement(String sql) {  
            int orderByStart = sql.toLowerCase().indexOf(ORDER_BY_TOKEN);  
            boolean isNeedFixNullFirst = orderByStart > -1;  
            if (!isNeedFixNullFirst) {  
                return super.onPrepareStatement(sql);  
            }  

            sql = StringUtils.replace(sql, " DESC ", " DESC NULLS LAST ");  
            sql = StringUtils.replace(sql, " DESC)", " DESC NULLS LAST)");  
            sql = StringUtils.replace(sql, " ASC ", " ASC NULLS LAST ");  
            sql = StringUtils.replace(sql, " ASC)", " ASC NULLS LAST)");

            logger.debug(sql);  
            return super.onPrepareStatement(sql);
        }

}

2:加入配置
applicationContext.xml

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocations">
            <list>
            <value>classpath:*.cfg.xml</value>
            </list>
        </property>
        <property name="entityInterceptor">
            <bean id="myNullsFirstInterceptor"              class="com.jnpm.util.MyNullsFirstInterceptor" />
      </property>
    </bean>

原文:http://czpae86.iteye.com/blog/1574915

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:23294次
    • 积分:525
    • 等级:
    • 排名:千里之外
    • 原创:26篇
    • 转载:24篇
    • 译文:0篇
    • 评论:0条