5 Replies - 9870 Views - Last Post: 13 May 2011 - 09:02 AM

#1 ShadowsEdge19   User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Connecting my program to MySQL database using Hibernate

Posted 13 May 2011 - 04:00 AM

Hi, I've recently been trying to create a Java to MySQL database link using Hibernate to map a Java class to a table of my database, the only problem I'm having is getting my program to connect to the database.

I've got these MySQL details:

MySQL database name: a1847282_animals
MySQL user name: a1847282_adam
Password for MySQL user: Password

Table name: Animals
field 1: animalID - int size 3
field 2: animalName - text size 20
field 3: animalType - text size 20

Here is the class that I am mapping:

public class AnimalsMapping {
    private int animalID;
    private String animalName;
    private String animalType;
    
    public AnimalsMapping(int id, String name, String type)
    {
        this.animalID = id;
        this.animalName = name;
        this.animalType = type;
    }
    
    public int getAnimalID()
    {
        return animalID;
    }
    
    public void setAnimalID(int newID)
    {
        this.animalID = newID;
    }
    
    public String getAnimalName()
    {
        return this.animalName;
    }
    
    public void setAnimalName(String newName)
    {
        this.animalName = newName;
    }
    
    public String getAnimalType()
    {
        return this.animalType;
    }
    
    public void setAnimalType(String newType)
    {
        this.animalType = newType;
    }
}


Here is the hibernate.cfg.xml file with the configuration details:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.url">mysql2.000webhost.com/a1847282_animals</property>
    <property name="hibernate.connection.username">a1847282_adam</property>
    <property name="hibernate.connection.password">Password</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!-- Mapping files -->
    <mapping resource="animal.hbm.xml"/>
  </session-factory>
</hibernate-configuration>



The Hibernate animal.hbm.xml Mapping file:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="animaldatabase.AnimalsMapping" table="Animals">
   <id name="animalID" type="int" column="animalID" >
  </id>
  
  <property name="animalName">
     <column name="animalName" />
  </property>
  <property name="animalType">
    <column name="animalType"/>
  </property>
 </class>
</hibernate-mapping>


animalsList is List<AnimalsMapping>
public void saveDatabase() 
    {
        try {
            // Write out Array to the database
            /* This step will read hibernate.cfg.xml and prepare hibernate for use*/
            SessionFactory sessionFactory = new 
                    Configuration().configure().buildSessionFactory();
            session =sessionFactory.openSession();
        
            for(int i = 0; i < animalsList.size(); i++)
            {
                try {
                    /*Create new instance of Contact and set 
                      values in it by reading them from form object*/
                    System.out.println("Inserting Record");
                    session.save(animalsList.get(i));
                }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            }
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
        finally{
            // Actual contact insertion will happen at this step
            session.flush();
            session.close();
        }
    }



Can anyone help me figure out what I've done wrong in the configuration settings or mapping?

This post has been edited by ShadowsEdge19: 13 May 2011 - 04:00 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Connecting my program to MySQL database using Hibernate

#2 macosxnerd101   User is offline

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12683
  • View blog
  • Posts: 45,866
  • Joined: 27-December 08

Re: Connecting my program to MySQL database using Hibernate

Posted 13 May 2011 - 04:09 AM

Moved to Java EE. Please reserve the Java Programmers forum for topical, non-help related discussion.
Was This Post Helpful? 0
  • +
  • -

#3 mi14chal   User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 202
  • Joined: 11-December 10

Re: Connecting my program to MySQL database using Hibernate

Posted 13 May 2011 - 08:23 AM

View PostShadowsEdge19, on 13 May 2011 - 01:00 PM, said:

problem I'm having is getting my program to connect to the database.


Are you getting any errors?
Was This Post Helpful? 0
  • +
  • -

#4 ShadowsEdge19   User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Connecting my program to MySQL database using Hibernate

Posted 13 May 2011 - 08:31 AM

I am, firstly I've updated my configuration file to this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.url">jdbc:mysql://mysql2.000webhost.com/a1847282_animals</property>
    <property name="hibernate.connection.username">a1847282_adam</property>
    <property name="hibernate.connection.password">passw0rd</property>
    
    <property name="connection.pool_size">1</property> 
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property> 
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
    
    <!-- Mapping files -->
    <mapping resource="animal.hbm.xml"/>
  </session-factory>
</hibernate-configuration>



and mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="animaldatabase.Animal" table="Animals">
   <id name="animalID" type="int" column="animalID" >
       <generator class="assigned" />
  </id>
  
  <property name="animalName">
     <column name="animalName" />
  </property>
  <property name="animalType">
    <column name="animalType"/>
  </property>
 </class>
</hibernate-mapping>


When I run a simple save I get this in the diagnostics:

13-May-2011 16:30:38 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
13-May-2011 16:30:38 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
13-May-2011 16:30:38 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
13-May-2011 16:30:38 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
13-May-2011 16:30:38 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
13-May-2011 16:30:38 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
13-May-2011 16:30:38 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : animal.hbm.xml
13-May-2011 16:30:39 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: animaldatabase.Animal -> Animals
13-May-2011 16:30:39 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
13-May-2011 16:30:39 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
13-May-2011 16:30:39 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 1
13-May-2011 16:30:39 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
13-May-2011 16:30:39 org.hibernate.connection.DriverManagerConnectionProvider configure
SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
	at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
	at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:169)
	at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:100)
	at org.hibernate.connection.DriverManagerConnectionProvider.configure(DriverManagerConnectionProvider.java:61)
	at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
	at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
	at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:414)
JDBC Driver class not found: com.mysql.jdbc.Driver
	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
	at animaldatabase.AnimalDatabase.saveDatabase(AnimalDatabase.java:109)
	at animaldatabase.AnimalDatabaseMain.showMainMenu(AnimalDatabaseMain.java:34)
	at animaldatabase.AnimalDatabaseMain.main(AnimalDatabaseMain.java:50)
Exception in thread "main" java.lang.NullPointerException
	at animaldatabase.AnimalDatabase.saveDatabase(AnimalDatabase.java:135)
	at animaldatabase.AnimalDatabaseMain.showMainMenu(AnimalDatabaseMain.java:34)
	at animaldatabase.AnimalDatabaseMain.main(AnimalDatabaseMain.java:50)
Java Result: 1


Was This Post Helpful? 0
  • +
  • -

#5 mi14chal   User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 202
  • Joined: 11-December 10

Re: Connecting my program to MySQL database using Hibernate

Posted 13 May 2011 - 08:49 AM

JDBC Driver class not found: com.mysql.jdbc.Driver Did you add JDBC Driver to your project?
Was This Post Helpful? 0
  • +
  • -

#6 ShadowsEdge19   User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Connecting my program to MySQL database using Hibernate

Posted 13 May 2011 - 09:02 AM

Okay I added the driver class to the library list.

But I'm getting some more errors, I'm not sure if the connection worked or if it was unable to send the data:

13-May-2011 16:59:31 org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
13-May-2011 16:59:31 org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
13-May-2011 16:59:31 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
13-May-2011 16:59:31 org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
13-May-2011 16:59:31 org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
13-May-2011 16:59:31 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
13-May-2011 16:59:32 org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : animal.hbm.xml
13-May-2011 16:59:32 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: animaldatabase.Animal -> Animals
13-May-2011 16:59:32 org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
13-May-2011 16:59:32 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
13-May-2011 16:59:32 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 1
13-May-2011 16:59:32 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
13-May-2011 16:59:32 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://mysql2.000webhost.com/a1847282_animals
13-May-2011 16:59:32 org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=a1847282_adam, password=****}
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
WARNING: Could not obtain connection metadata
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 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.
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
	at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
	at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:343)
	at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2308)
	at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2122)
	at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:774)
	at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
	at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:375)
	at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:289)
	at java.sql.DriverManager.getConnection(DriverManager.java:582)
	at java.sql.DriverManager.getConnection(DriverManager.java:154)
	at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
	at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84)
	at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
	at animaldatabase.AnimalDatabase.saveDatabase(AnimalDatabase.java:109)
	at animaldatabase.AnimalDatabaseMain.showMainMenu(AnimalDatabaseMain.java:34)
	at animaldatabase.AnimalDatabaseMain.main(AnimalDatabaseMain.java:50)
Caused by: java.net.ConnectException: Connection timed out: connect
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
	at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
	at java.net.Socket.connect(Socket.java:519)
	at java.net.Socket.connect(Socket.java:469)
	at java.net.Socket.<init>(Socket.java:366)
	at java.net.Socket.<init>(Socket.java:208)
	at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
	at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:292)
	... 20 more
13-May-2011 16:59:54 org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
13-May-2011 16:59:54 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
13-May-2011 16:59:54 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
13-May-2011 16:59:54 org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
13-May-2011 16:59:54 org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
13-May-2011 16:59:54 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Exception in thread "main" java.lang.NullPointerException
	at animaldatabase.AnimalDatabase.saveDatabase(AnimalDatabase.java:135)
	at animaldatabase.AnimalDatabaseMain.showMainMenu(AnimalDatabaseMain.java:34)
	at animaldatabase.AnimalDatabaseMain.main(AnimalDatabaseMain.java:50)
Java Result: 1



Edit: It's stuck at the connection phase still, is the connection url correct using the connection details in the first post?

This post has been edited by ShadowsEdge19: 13 May 2011 - 09:17 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1