需要帮助:Hibernate Criteria在4.3中有效,而在5.3.7中无效

时间:2018-10-18 20:58:12

标签: hibernate

我的任务是将旧版企业应用程序从Hibernate 4.3.5迁移到5.3.7并升级到Java10。我们的应用程序使用org.hibernate.Criteria查询我们的数据库。这可以正常工作并在Hibernate 4.3.5(Java 10)中返回数据,但是当编译并与Hibernate 5.3.7(Java 10)一起运行时,我们对Criteria.list()的调用将返回一个空列表(不引发任何异常)。这是一段示例代码,它使用Hibernate 4.3.5(而非5.3.7)返回数据。如果有人指出我需要更改的内容,那就太好了。顺便说一句,由于我们的应用程序大小更改为使用CriteriaBuilder和CriteriaQuery超出了项目范围。

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class TestHibernate {

    private static String gHibernateCfgXMLFile = "hibernate.cfg.xml";
    private static ServiceRegistry serviceRegistry = null;
    private static SessionFactory gSessionFactory = null;

    public TestHibernate() throws Exception {
        Session fSession = null;
        try {
            Configuration fHibernateCfg = new Configuration();
            fHibernateCfg.configure(gHibernateCfgXMLFile);
            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(fHibernateCfg.getProperties()).build();
            gSessionFactory = fHibernateCfg.buildSessionFactory(serviceRegistry);
            System.out.println("*****************  Users load starting.");
            fSession = gSessionFactory.openSession();
            Criteria fCriteria = fSession.createCriteria(Users.class);
            List<Users> fList = fCriteria.list();
            for (Users fSC : fList) {
                String fName = fSC.getLogon();
                System.out.println("*****************  Users loaded:  [" + fName + "].");
            }
            long fSize = fList.size();
            System.out.println("*********  Users read:  " + fSize + " POJOs.");
        }
        catch(Exception e) {
            System.out.println("Error testing DB connection");
            throw new Exception("Error testing DB connection", e);
        }
        finally {
            try { fSession.close(); } catch(Exception e) { System.out.println("Error closing conection while testing DB connection"); }
        }
    }

    public static void main(String[] args) throws Exception {
        new TestHibernate();
    }

}

1 个答案:

答案 0 :(得分:0)

弄清楚了。将会话工厂的创建更改为:

final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
            gSessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();