Конфигурация hibernate 5 для oracle11g в eclipse

Я пытаюсь настроить спящий режим 5 для доступа к оракулу 11 g в eclipse.

hibernate.cfg.xml выглядит следующим образом:

В следующем xml я указал учетные данные базы данных (url, имя пользователя и пароль), дилект, класс сопоставления, show_sql . Я хочу спросить, не пропустил ли я какое-либо важное свойство.

<?xml version='1.0' encoding='utf-8'?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!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>

        <!-- Database connection settings -->
        <!-- <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
                    <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> -->

        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>
        <property name="connection.username">SYSTEM</property>
        <property name="connection.password">motog</property>

        <mapping class="com.demo.one.Hello"/>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.OracleDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <property name="cache.use_query_cache">true</property>
        <property name="cache.use_second_level_cache">true</property>
        <property name="cache.use_structured_entries">true</property>
        <property name="cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
        <property name="net.sf.ehcache.configurationResourceName">/hibernate-config/ehcache.xml</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <mapping resource="hibernate-config/domain/Event.hbm.xml"/>
        <mapping resource="hibernate-config/domain/Person.hbm.xml"/>
        <mapping resource="hibernate-config/domain/PhoneNumber.hbm.xml"/>
        <mapping resource="hibernate-config/domain/Account.hbm.xml"/>
        <mapping resource="hibernate-config/domain/HolidayCalendar.hbm.xml"/>

        <mapping resource="hibernate-config/domain/Item.hbm.xml"/>

    </session-factory>

</hibernate-configuration>


[image specifies project structure and imported libraries][1]

Определенный класс Hello как имя таблицы с использованием @Entity и userId в качестве первичного ключа с использованием @Id

Привет.java:

    package com.demo.one;

    import javax.persistence.Entity;
    import javax.persistence.Id;

    @Entity
    public class Hello {
        @Id
    private int userId;
    private String userName;

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

    } // end of Hello.java

Следующий класс пытается сохранить экземпляр Hello в базе данных.

OracleTest.java:

    package com.demo.one;

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;

    public class OracleTest {

        public static void main(String[] args) {
            Hello z = new Hello();
            z.setUserId(2);
            z.setUserName("ashish");
            SessionFactory sf = new                                Configuration().configure().buildSessionFactory();
            Session session = sf.openSession();
            session.beginTransaction();
            session.save(z);
            session.getTransaction().commit();

        }

    } // End of OracleTest.java

Я пытаюсь сохранить объект класса Hello в базе данных oracle 11g XE (находится на моей локальной машине), для этого написан OracleTest.java.

Я получаю следующие ошибки.

Jan 17, 2016 6:08:01 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.7.Final}
Jan 17, 2016 6:08:01 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 17, 2016 6:08:01 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number -1 and column -1 in RESOURCE hibernate.cfg.xml. Message: cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    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 com.demo.one.OracleTest.main(OracleTest.java:13)
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException; cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.]
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
    ... 6 more
Caused by: org.xml.sax.SAXParseException; cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(Unknown Source)
    ... 9 more

please guide me, its my first encounter with hibernate. 

PS: please check attached image. link is at the bottom.

regards
ashish



  [1]: http://i.stack.imgur.com/DBYxu.png

person Ashish Parab    schedule 17.01.2016    source источник


Ответы (1)


Сообщение об ошибке сообщает вам, что где-то не ожидается элемент <property>. Вместо этого он ожидает элемент <mapping>, или элемент <class-cache>, или...

И действительно, DTD имеет следующее определение:

<!ELEMENT session-factory (property*, mapping*, (class-cache|collection-cache)*, event*, listener*)>

Это означает, что в <session-factory> у вас должно быть 0 или более элементов <property>, а затем 0 или более элементов <mapping>.

Но ваш xml-файл имеет

<property name="connection.password">motog</property>

<mapping class="com.demo.one.Hello"/>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

Итак, у вас есть <mapping>элемент в середине <property> элементов. Таким образом, это недействительно.

person JB Nizet    schedule 17.01.2016