19

I'm just trying to learn Hibernate (version 4 final) but I have a problem when trying to create the session factory. Here is some code related to the problem:

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;
    }
}


Now, what seems to be the problem is creating the ServiceRegistryBuilder. When the code execution gets to that point, it gives me the following error:

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'.



full error log:

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)


How do I fix this? I can't seem to find a solution myself.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Fittersman
  • 625
  • 2
  • 11
  • 22
  • For now, I'm just using the following to generate the SessionFactory: "new AnnotationConfiguration().configure().buildSessionFactory();" It works, however it's depricated so I'd like to avoid using it if possible. – Fittersman Dec 27 '11 at 11:48

9 Answers9

25

The methods buildSessionFactory and ServiceRegistryBuilder in Hibernate 4.3.4 are deprecated.

The right code is here.

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();
            ........
saneryee
  • 3,239
  • 31
  • 22
11

As of 4.3.0, even ServiceRegistryBuilder has been deprecated. This is how you would want to go about it

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

And also you would have to import org.hibernate.boot.registry.StandardServiceRegistryBuilder instead of org.hibernate.service.ServiceRegistryBuilder

idok
  • 642
  • 10
  • 24
  • This configuration above did not read my mappings though a variant of this below did. ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(). configure().loadProperties("hibernate.cfg.xml").build(); sessionFactory = new Configuration().buildSessionFactory(serviceRegistry); – veritas Jan 25 '21 at 04:30
6

I encountered similar problems trying to use Hibernate 4.1.6.

Building on an example from RoseIndia.net, I got ServiceRegistryBuilder working like this:

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

My hibernate.cfg.xml file uses the old DTD file; I have not been able to get the new XSD file to be recognized by 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>

Perhaps you can adapt this to work for you?

5

Here is how it works with 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>

rest of configuration remains same

Keerthi
  • 80
  • 2
  • 7
1

for the below error :

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)

we should place the hibernate.cfg.xml in src folder..

Abhinav Singh Maurya
  • 3,313
  • 8
  • 33
  • 51
perky
  • 11
  • 1
0

// hibernate 4构建sessionFactory方式 email 563143188@qq.com

    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();

// test is ok

Jin Kim
  • 16,562
  • 18
  • 60
  • 86
0

It might be just nitpicking, but please try replacing the DOCTYPE declaration in hibernate.cfg.xml with this:

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

Also, declare a name for the session-factory:

<session-factory name="java:hibernate/SessionFactory">
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thanks for the reply, but that didn't seem to do anything for me. Any other ideas? – Fittersman Dec 27 '11 at 11:47
  • Well, the log indicates an error in `hibernate.cfg.xml`, but it looks fine from here. Maybe a problem with the encoding of the file? make sure it's indeed UTF-8 – Óscar López Dec 27 '11 at 13:58
  • I'm not really sure, I'm starting to wonder if there is a bug in there somewhere because after reading online for a while that's the impression I'm getting. For now, I'll just stick with the old way of getting the session factory. I'll try again later to use the new way since it doesn't look like anyone on here has an answer sadly :( – Fittersman Dec 28 '11 at 12:18
0

Here is the deprecated method from Configuration that still works. It is doing a lot of hibernate specific setup that hibernate users wouldn't really want to do. Things like veryifying properties and copying them from one object to another. I have also been looking for a working example of Hibernate configuration for Hibernate 4 that does not use the deprecated buildSessionFactory() method and have been unable to find one so far. I believe that the intent is to deprecate Configuration entirely.

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 );
}
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
0

As answered in hibernate 4.0.0. CR4: org.hibernate.internal.util.config.ConfigurationException with hibernate.cfg.xml, the new way of creating SessionFactories doesn't work yet. It will be ready in Hibernate 4.1.

Community
  • 1
  • 1
Thiago Chaves
  • 9,218
  • 5
  • 28
  • 25