Ошибка интеграции HibernateSearch ElasticSearch: исключение в потоке "main" java.lang.ExceptionInInitializerError - PullRequest
0 голосов
/ 24 апреля 2018

Пытаюсь настроить HibernateSearch для интеграции ElasticSearch.Получаю приведенную ниже ошибку от HibernateSearch:

Использую базу данных Oracle и добавил необходимые зависимости в мой файл pom.xml

Пожалуйста, найдите мою ошибку:

Exception in thread "main" java.lang.ExceptionInInitializerError
at com.test.webservice.elasticsearch.App.displayContactTableData(App.java:50)
at com.test.webservice.elasticsearch.App.main(App.java:70)
Caused by: java.lang.NullPointerException
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.<init>(MetadataBuilderImpl.java:579)
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:127)
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:654)
at com.test.webservice.elasticsearch.HibernateUtil.configureSessionFactory(HibernateUtil.java:36)
at com.test.webservice.elasticsearch.HibernateUtil.<clinit>(HibernateUtil.java:44)
... 2 more

Его ошибка в HibernateUtil.java для строки ниже:

    sessionFactory = configuration.buildSessionFactory(serviceRegistry);  

Использую все последние зависимости.

hibernate-search-orm ->5.9.1.Final  
hibernate-core ->5.2.16.Final 
ojdbc14 -> 10.2.0.4.0

hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>

    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
    <property name="hibernate.connection.username">testdb</property>
    <property name="hibernate.connection.password">123456</property>
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="show_sql">false</property>
    <property name="format_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.search.default.directory_provider">filesystem</property>
    <property name="hibernate.search.default.indexBase">C:\lucene\product\indexes</property>

    <mapping class="com.test.webservice.model.Product" />

    </session-factory>
</hibernate-configuration>

HibernateUtil.java

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

    public class HibernateUtil {

        private static SessionFactory sessionFactory = null;  
        private static ServiceRegistry serviceRegistry = null;  

        private static SessionFactory configureSessionFactory() throws HibernateException {  
        Configuration configuration = new Configuration();  
        configuration.configure();  

        Properties properties = configuration.getProperties();
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(properties).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);  

        return sessionFactory;  
    }
    static {
        configureSessionFactory();
    }

    private HibernateUtil() {}

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

App.java

public class App 
{
    private static void doIndex() throws InterruptedException {
        Session session = HibernateUtil.getSession();

        FullTextSession fullTextSession = Search.getFullTextSession(session);
        fullTextSession.createIndexer().startAndWait();

        fullTextSession.close();
    }

    private static List<Product> search(String queryString) {
        Session session = HibernateUtil.getSession();
        FullTextSession fullTextSession = Search.getFullTextSession(session);

        QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();
        org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("name").matching(queryString).createQuery();

        // wrap Lucene query in a javax.persistence.Query
        org.hibernate.Query fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, Product.class);

        List<Product> productList = fullTextQuery.list();

        fullTextSession.close();

        return productList;
    }

    private static void displayContactTableData() {
        Session session = null;

        try {
            session = HibernateUtil.getSession();

            // Fetching saved data
            List<Product> productList = session.createQuery("from Product").list();

            for (Product product : productList) {
                System.out.println(product);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally{
            if(session != null) {
                session.close();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("\n\n******Data stored in Contact table******\n");
        displayContactTableData();

        // Create an initial Lucene index for the data already present in the database
        doIndex();

        Scanner scanner = new Scanner(System.in);
        String consoleInput = null;

        while (true) {
            // Prompt the user to enter query string
            System.out.println("\n\nEnter search key (To exit type 'X')");      
            System.out.println();
            consoleInput = scanner.nextLine();

            if("X".equalsIgnoreCase(consoleInput)) {
                System.out.println("End");
                System.exit(0);
            }   

            List<Product> result = search(consoleInput);            
            System.out.println("\n\n>>>>>>Record found for '" + consoleInput + "'");

            for (Product product : result) {
                System.out.println(product);
            }               
        }           
    }
}

1 Ответ

0 голосов
/ 24 апреля 2018

Ваш код объявляет две ServiceRegistry переменные: sr и serviceRegistry. serviceRegistry содержит null, когда вы передаете его configuration.buildSessionFactory, потому что вы помещаете значение в sr.

Выберите одну переменную, используйте ее правильно, удалите другую, и все будет в порядке.

...