web-dev-qa-db-fra.com

Hibernate - ServiceRegistryBuilder

J'essaie juste d'apprendre Hibernate (version 4 finale), mais j'ai un problème lorsque j'essaie de créer la fabrique de sessions. Voici un code lié au problème:

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="connection.url">jdbc:mysql://localhost/fitterblog</property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

    <property name="connection.pool_size">1</property>
    <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="current_session_context_class">thread</property>
    <property name="show_sql">true</property>

    <!--<mapping class="com.fitterblog.objects.Article"/>
    <mapping class="com.fitterblog.objects.Nav"/>
    <mapping class="com.fitterblog.objects.Tag"/>
    <mapping class="com.fitterblog.objects.User"/>-->

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


HibernateUtil.Java:

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml

            ServiceRegistryBuilder srb = new ServiceRegistryBuilder();

            //NOTE: THIS IS WHERE MY PROGRAM DIES!!
            srb = srb.configure();

            ServiceRegistry sr = srb.buildServiceRegistry();
            MetadataSources mds = new MetadataSources(sr);
            /*mds.addAnnotatedClass(com.fitterblog.objects.Article.class);
            mds.addAnnotatedClass(com.fitterblog.objects.Nav.class);
            mds.addAnnotatedClass(com.fitterblog.objects.Tag.class);
            mds.addAnnotatedClass(com.fitterblog.objects.User.class);*/
            return mds.buildMetadata().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}


Maintenant, le problème semble être la création de ServiceRegistryBuilder. Lorsque l'exécution du code arrive à ce point, cela me donne l'erreur suivante:

org.hibernate.internal.util.config.ConfigurationException: 
Unable to perform unmarshalling at line number 14 and 
column 26 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1:
Cannot find the declaration of element 'hibernate-configuration'.



journal des erreurs complet:

run:
Dec 27, 2011 12:51:12 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.0.Final}
Dec 27, 2011 12:51:12 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 27, 2011 12:51:12 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Initial SessionFactory creation failed. org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 14 and column 26 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
Exception in thread "main" Java.lang.ExceptionInInitializerError
at com.fitterblog.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.Java:33)
at com.fitterblog.hibernate.HibernateUtil.<clinit>(HibernateUtil.Java:18)
at com.fitterblog.objects.Article.list(Article.Java:31)
at main.main(main.Java:20)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 14 and column 26 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at org.hibernate.service.internal.JaxbProcessor.unmarshal(JaxbProcessor.Java:120)
at org.hibernate.service.internal.JaxbProcessor.unmarshal(JaxbProcessor.Java:69)
at org.hibernate.service.ServiceRegistryBuilder.configure(ServiceRegistryBuilder.Java:162)
at org.hibernate.service.ServiceRegistryBuilder.configure(ServiceRegistryBuilder.Java:147)
at com.fitterblog.hibernate.HibernateUtil.buildSessionFactory(HibernateUtil.Java:23)
... 3 more
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 26; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.Java:419)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.Java:356)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.Java:326)
at org.hibernate.service.internal.JaxbProcessor.unmarshal(JaxbProcessor.Java:108)
... 7 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 26; cvc-elt.1:       Cannot find the declaration of element 'hibernate-configuration'.
at com.Sun.org.Apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.Java:198)
at com.Sun.org.Apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.Java:134)
at com.Sun.org.Apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.Java:437)
at com.Sun.org.Apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.Java:368)
at com.Sun.org.Apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.Java:325)
at com.Sun.org.Apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.Java:1897)
at com.Sun.org.Apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.Java:737)
at com.Sun.org.Apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(ValidatorHandlerImpl.Java:564)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.Java:86)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.Java:60)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.Java:232)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.Java:166)
at com.Sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.Java:354)
... 9 more
Java Result: 1
BUILD SUCCESSFUL (total time: 7 seconds)


Comment puis-je réparer ça? Je n'arrive pas à trouver une solution moi-même.

16
Fittersman

Les méthodes buildSessionFactory et ServiceRegistryBuilder dans Hibernate 4.3.4 sont obsolètes.

Le bon code est ici.

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


.....

    Configuration conf = new Configuration()
              .configure();


    ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();


    SessionFactory sf = conf.buildSessionFactory(sr);

    Session session = sf.openSession();

    session.beginTransaction();


    YourDominClass ydc = new YourDominClass();

    ydc.setSomething("abcdefg");

    session.save(ydc);

    session.getTransaction().commit();

    session.close();

    sf.close();
            ........
17
saneryee

Depuis la version 4.3.0, même ServiceRegistryBuilder était obsolète. Voici comment vous voudriez vous y prendre 

Configuration cfg=new Configuration().configure();
StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder().applySettings(
            cfg.getProperties());
SessionFactory factory= cfg.buildSessionFactory(builder.build());

Et vous devrez aussi importer org.hibernate.boot.registry.StandardServiceRegistryBuilder au lieu de org.hibernate.service.ServiceRegistryBuilder

9
idok

Voici comment cela fonctionne avec hibernate 4.x

<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration xmlns="http://www.hibernate.org/xsd/hibernate-configuration">
    <session-factory name="Java:hibernate/SessionFactory"><!-- Name is Optional -->
......
</session-factory>
</hibernate-configuration>

reste de la configuration reste la même

5
Keerthi

J'ai rencontré des problèmes similaires en essayant d'utiliser Hibernate 4.1.6.

En me basant sur un exemple de RoseIndia.net , ServiceRegistryBuilder fonctionne comme suit:

Configuration config = new Configuration();
config.configure();
ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder();
srBuilder.applySettings(config.getProperties());
ServiceRegistry serviceRegistry = srBuilder.buildServiceRegistry();
SessionFactory factory = config.buildSessionFactory(serviceRegistry);

Mon fichier hibernate.cfg.xml utilise l'ancien fichier DTD; Je n'ai pas réussi à faire reconnaître le nouveau fichier XSD par Hibernate 4.1.6:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        ...
    </session-factory>
</hibernate-configuration>

Peut-être que vous pouvez adapter cela pour travailler pour vous?

5
Lennart Månsson

pour l'erreur ci-dessous:

Oct 09, 2015 12:29:53 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
Oct 09, 2015 12:29:53 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 09, 2015 12:29:53 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.Java:53)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.Java:163)
    at org.hibernate.cfg.Configuration.configure(Configuration.Java:259)
    at org.hibernate.cfg.Configuration.configure(Configuration.Java:245)
    at org.hibernate.ClientResource.ClientTest.main(ClientTest.Java:17)

nous devrions placer le fichier hibernate.cfg.xml dans le dossier src.

1
perky

// hibernate 4, sessionFactory, email [email protected]

    Configuration cfg = new Configuration()
            .configure("hibernate.cfg.xml");

    SessionFactory sf = cfg.buildSessionFactory(new ServiceRegistryBuilder()
            .applySettings(cfg.getProperties()).build());
    //build()   return buildServiceRegistry
    Session s = sf.openSession();

// le test est ok

0
user2473488

Comme répondu dans hibernate 4.0.0. CR4: org.hibernate.internal.util.config.ConfigurationException avec hibernate.cfg.xml , la nouvelle méthode de création de SessionFactories ne fonctionne pas encore. Il sera prêt dans Hibernate 4.1.

0
Thiago Chaves

Voici la méthode obsolète de Configuration qui fonctionne toujours. Il fait beaucoup de configurations spécifiques à l'hibernation que les utilisateurs de l'hibernation ne voudraient pas vraiment faire. Des choses comme modifier des propriétés et les copier d'un objet à un autre. Je recherchais également un exemple concret de configuration d'Hibernate pour Hibernate 4 n'utilisant pas la méthode obsolète buildSessionFactory () et n'ayant pu en trouver aucun. Je crois que l’intention est de déprécier totalement la configuration.

public SessionFactory buildSessionFactory() throws HibernateException {
    Environment.verifyProperties( properties );
    ConfigurationHelper.resolvePlaceHolders( properties );
    final ServiceRegistry serviceRegistry =  new ServiceRegistryBuilder()
            .applySettings( properties )
            .buildServiceRegistry();
    setSessionFactoryObserver(
            new SessionFactoryObserver() {
                @Override
                public void sessionFactoryCreated(SessionFactory factory) {
                }

                @Override
                public void sessionFactoryClosed(SessionFactory factory) {
                    ( (StandardServiceRegistryImpl) serviceRegistry ).destroy();
                }
            }
    );
    return buildSessionFactory( serviceRegistry );
}
0
Stephen Ostermiller

C'est peut-être un peu piquant, mais essayez de remplacer la déclaration DOCTYPE dans hibernate.cfg.xml par ceci:

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

Déclarez également un nom pour l’usine de session:

<session-factory name="Java:hibernate/SessionFactory">
0
Óscar López