Hibernate + MySql DB + Tomcat - Не може да се установи връзка

Възможен дубликат:
Конфигуриране хибернация за свързване с база данни чрез JNDI Datasource

Опитвам се да получа достъп до базата данни чрез хибернация, но получавам Configured SessionFactory: null. Имам mysql конектора db в моята папка tomcat/lib, а не в моя проект. Но мисля, че трябва да работи така.

За MySQL DB:

Context.xml

                    <?xml version="1.0" encoding="UTF-8"?>

    <Context>

    <!-- myDatabase = database name -->

     <Resource name="jdbc/myDatabase" 

                  auth="Container"

                  type="javax.sql.DataSource" 

                  username="admin" 

                  password="geheim"

                  driverClassName="com.mysql.jdbc.Driver"

                  url="jdbc:mysql://localhost:3306/myDatabase"

                  maxActive="15" 

                  maxIdle="3"/>

    </Context>

web.xml:

    <!-- DB -->
     <resource-ref>
       <description>MyDatabase Description</description>
        <res-ref-name>jdbc/myDatabase</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
     </resource-ref>

Хибернация

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>
            <!-- Database connection settings -->
                <!-- <property name="connection.datasource">java:comp/env/jdbc/myDatabase</property>-->
                <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>
                <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
                <property name="current_session_context_class">thread</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">admin</property>
        <property name="hibernate.connection.password">geheim</property>

                <!-- <mapping resource="com/bachelor/EstateDTO.hbm.xml"/> -->
                <mapping resource="com/bachelor/hibernateobject/Event.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

Утил:

    public class HibernateUtil {
        private static SessionFactory sessionFactory;
        private static ServiceRegistry serviceRegistry;

        public static SessionFactory buildSessionFactory() {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
                Configuration configuration = new Configuration();
                System.out.println("1");
                configuration.configure();
                System.out.println("2");
                serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();    
                System.out.println("3");
                return new Configuration().configure().buildSessionFactory(serviceRegistry);
            } catch (Throwable ex) {
                // Make sure you log the exception, as it might be swallowed
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }

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

Обадете се

Връзката mysql db работи с:

            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            System.out.println(envCtx);
            DataSource ds = (DataSource) envCtx.lookup("jdbc/myDatabase");
            System.out.println(ds);

Повикването за хибернация не:

 Session session = HibernateUtil.buildSessionFactory().openSession();
    session.beginTransaction();

    Event theEvent = new Event();
    theEvent.setTitle("My Event");
    theEvent.setDate(new Date());
    session.save(theEvent);

    session.save(theEvent);

    session.getTransaction().commit();

Проследяване на стека:

06.07.2012 16:52:09 com.sun.jersey.server.impl.application.WebApplicationImpl   _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.12 02/15/2012 04:51 PM'
06.07.2012 16:52:09     com.sun.jersey.server.impl.application.DeferredResourceConfig$ApplicationHolder     <init>
INFO: Instantiated the Application class com.bachelor.core.MyApplication
06.07.2012 16:52:11 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
06.07.2012 16:52:11 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.3.Final}
06.07.2012 16:52:11 org.hibernate.cfg.Environment <clinit>
NFO: HHH000206: hibernate.properties not found
06.07.2012 16:52:11 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
1
06.07.2012 16:52:11 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
06.07.2012 16:52:11 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
06.07.2012 16:52:11 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource:    com/bachelor/hibernateobject/Event.hbm.xml
06.07.2012 16:52:11 org.hibernate.internal.util.xml.DTDEntityResolver   resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace    http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/  instead. Refer to Hibernate 3.6 Migration Guide!
06.07.2012 16:52:11 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
2
3
06.07.2012 16:52:11 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
06.07.2012 16:52:11 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
06.07.2012 16:52:11 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource:    com/bachelor/hibernateobject/Event.hbm.xml
06.07.2012 16:52:11 org.hibernate.internal.util.xml.DTDEntityResolver   resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace h  ttp://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/   instead. Refer to Hibernate 3.6 Migration Guide!
06.07.2012 16:52:11 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
06.07.2012 16:52:11 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
06.07.2012 16:52:11     org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
06.07.2012 16:52:11     org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl     configure
INFO: HHH000006: Autocommit mode: false
06.07.2012 16:52:11     org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl     configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL    [jdbc:mysql://localhost:3306/myDatabase]
06.07.2012 16:52:11     org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl     configure
INFO: HHH000046: Connection properties: {user=admin, password=****}
06.07.2012 16:52:14 org.hibernate.engine.jdbc.internal.JdbcServicesImpl configure
WARN: HHH000342: Could not obtain connection to query metadata : Communications     link failure

The last packet sent successfully to the server was 0 milliseconds ago. The     driver has not received any packets from the server.
06.07.2012 16:52:14 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
06.07.2012 16:52:14 org.hibernate.engine.jdbc.internal.LobCreatorBuilder    useContextualLobCreation
INFO: HHH000422: Disabling contextual LOB creation as connection was null
06.07.2012 16:52:14     org.hibernate.engine.transaction.internal.TransactionFactoryInitiator   initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
06.07.2012 16:52:14 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
06.07.2012 16:52:16 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08S01
06.07.2012 16:52:16 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The     driver has not received any packets from the server.
06.07.2012 16:52:16 com.sun.jersey.spi.container.ContainerResponse  mapMappableContainerException
SCHWERWIEGEND: The RuntimeException could not be mapped to a response, re-  throwing to the HTTP container
org.hibernate.exception.JDBCConnectionException: Could not open connection
at  org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at  org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at o    rg.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at

Изглежда, че приложението може да изгради връзка към db директно, но не и чрез хибернация.

редактиране:

Какво не е наред с моя url път в моя hibernate.cfg.xml?

редактиране:

Зависимости на хибернация:

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>4.1.3.Final</version>
            </dependency>

            <!-- Because this is a web app, we also have a dependency on the servlet api. -->
            <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>servlet-api</artifactId>
        <version>6.0.35</version>
    </dependency>

            <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
                <version>1.6.4</version>
            </dependency>

            <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist -->
            <dependency>
                <groupId>javassist</groupId>
                <artifactId>javassist</artifactId>
                <version>3.12.1.GA</version>
            </dependency>

                    <!-- Hibernate library dependecy end -->

        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

person Robin Wieruch    schedule 06.07.2012    source източник
comment
Къде поставихте файла hibernate.cfg.xml, също и какви библиотеки за хибернация поставихте?   -  person Ramanqul Buzaubak    schedule 06.07.2012
comment
cfg е в папката src/main/java. хибернация на зависимости, редактирана по-горе.   -  person Robin Wieruch    schedule 06.07.2012
comment
Не получавам друго изключение. Изглежда, че няма нищо за водача. Може би URL адресът е грешен?   -  person Robin Wieruch    schedule 06.07.2012
comment
Опитахте ли Използване на Hibernate с Tomcat, аз го направих, но без maven и всичко работи добре!   -  person Ramanqul Buzaubak    schedule 06.07.2012
comment
можете ли да дадете бърз преглед на вашите стъпки и може би вашия cgf и context.xml?   -  person Robin Wieruch    schedule 06.07.2012


Отговори (1)


Кодът работеше. Само MySQL сървъра не стартира.

person Robin Wieruch    schedule 08.07.2012
comment
какво имаш предвид, можеш ли да разясниш, моля? - person Siddharth; 30.09.2014
comment
Работи с предишния код. Инсталацията на моя MySQL сървър не стартира. - person Robin Wieruch; 30.09.2014
comment
Не започнах, прав път са много двусмислени. Наистина се надявам да отделите време, за да отговорите правилно и изчерпателно. Благодаря. - person Siddharth; 01.10.2014