-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 posts ] 
Author Message
 Post subject: How to generate data base schema?
PostPosted: Sun Feb 14, 2010 11:50 am 
Newbie

Joined: Mon Jan 18, 2010 6:44 pm
Posts: 11
This is my project Image

HelloWorld.java

Code:
package hello;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import persistence.HibernateUtil;

public class HelloWorld {
   
   public static void main(String[] args) {
      // First unit of work
      Session session = HibernateUtil.getSessionFactory().openSession();
      Transaction tx = session.beginTransaction();
      Message message = new Message("Hello World");
      Long msgId = (Long) session.save(message);
      tx.commit();
      session.close();
      // Second unit of work
      Session newSession = HibernateUtil.getSessionFactory().openSession();
      Transaction newTransaction = newSession.beginTransaction();
      List messages = newSession.createQuery("from Message m order by m.text asc").list();
      System.out.println( messages.size() + " message(s) found:" );
      for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
         Message loadedMsg = (Message) iter.next();
         System.out.println( loadedMsg.getText() );
      }
      newTransaction.commit();
      newSession.close();
      // Shutting down the application
      HibernateUtil.shutdown();
   }
}


Message.java

Code:
package hello;
public class Message {
   private Long id;
   private String text;
   private Message nextMessage;
   
   Message() {
      
   }
   
   public Message(String text) {
      this.text = text;
   }
   
   public Long getId() {
      return id;
   }
   
   @SuppressWarnings("unused")
   private void setId(Long id) {
      this.id = id;
   }
   
   public String getText() {
      return text;
   }
   
   public void setText(String text) {
      this.text = text;
   }
   
   public Message getNextMessage() {
      return nextMessage;
   }
   
   public void setNextMessage(Message nextMessage) {
      this.nextMessage = nextMessage;
   }
}


Message.hbm.xml

Quote:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hello.Message" table="MESSAGES">
<id name="id" column="MESSAGE_ID">
<generator class="increment"/>
</id>
<property name="text" column="MESSAGE_TEXT"/>
<many-to-one name="nextMessage" cascade="all" column="NEXT_MESSAGE_ID" foreign-key="FK_NEXT_MESSAGE"/>
</class>
</hibernate-mapping>


HibernateUtil.java

Quote:
package persistence;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
// Alternatively, you could look up in JNDI here
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}


hibernate.cfg.xml

Code:
<!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.Oracle10gDialect</property>
      <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
      <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
      <property name="hibernate.connection.username">employeer</property>
      <property name="hibernate.connection.password">employeer</property>

       <!-- JDBC connection pool (use the built-in) -->
       <property name="connection.pool_size">1</property>
       
      <!-- Important! addendum to what is in text -->
      <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</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 - You can disable this once you have it working -->
       <property name="show_sql">true</property>
   
   </session-factory>
</hibernate-configuration>


log4j.properties
Code:
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE}
%5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=INFO, stdout
# Hibernate logging options (INFO only shows startup messages)
log4j.logger.org.hibernate=INFO
# Log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=INFO


build.xml

Code:
<project name="HelloWorld" default="compile" basedir=".">
   <!-- Name of project and version -->
   <property name="proj.name" value="HelloWorld"/>
   <property name="proj.version" value="1.0"/>
   <!-- Global properties for this build -->
   <property name="src.java.dir" value="src"/>
   <property name="lib.dir" value="lib"/>
   <property name="build.dir" value="bin"/>
   <!-- Classpath declaration -->
   <path id="project.classpath">
      <fileset dir="${lib.dir}">
         <include name="**/*.jar"/>
         <include name="**/*.zip"/>
      </fileset>
   </path>
   <!-- Useful shortcuts -->
   <patternset id="meta.files">
      <include name="**/*.xml"/>
      <include name="**/*.properties"/>
   </patternset>
   <!-- Clean up -->
   <target name="clean">
      <delete dir="${build.dir}"/>
      <mkdir dir="${build.dir}"/>
   </target>
   <!-- Compile Java source -->
   <target name="compile" depends="clean">
      <mkdir dir="${build.dir}"/>
      <javac srcdir="${src.java.dir}" destdir="${build.dir}" nowarn="on">
         <classpath refid="project.classpath"/>
      </javac>
   </target>
   <!-- Copy metadata to build classpath -->
   <target name="copymetafiles">
      <copy todir="${build.dir}">
         <fileset dir="${src.java.dir}">
            <patternset refid="meta.files"/>
         </fileset>
      </copy>
   </target>
   <target name="schemaexport" depends="compile, copymetafiles" description="Exports a generated schema to DB and file">
      <hibernatetool destdir="${basedir}">
         <classpath path="${build.dir}"/>
         <configuration
         configurationfile="${build.dir}/hibernate.cfg.xml"/>
         <hbm2ddl
         drop="true"
         create="true"
         export="true"
         outputfilename="helloworld-ddl.sql"
         delimiter=";"
         format="true"/>
      </hibernatetool>
   </target>
</project>


I run build.xml but it not generate helloworld-ddl.sql... And when I run HelloWorld.java I got these errors

Code:
Feb 14, 2010 4:40:06 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.3.2.GA
Feb 14, 2010 4:40:06 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Feb 14, 2010 4:40:06 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : javassist
Feb 14, 2010 4:40:06 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Feb 14, 2010 4:40:06 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Feb 14, 2010 4:40:06 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
   at persistence.HibernateUtil.<clinit>(Unknown Source)
   at hello.HelloWorld.main(Unknown Source)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
   at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
   at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1453)
   at org.hibernate.cfg.Configuration.configure(Configuration.java:1475)
   at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
   ... 2 more


where do I made a mistake???
please help!!! :)


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Mon Feb 15, 2010 8:02 am 
Newbie

Joined: Thu Feb 11, 2010 2:05 pm
Posts: 4
Location: Ghent, Belgium
The log tells you that it cant find the file "hibernate.cfg.xml" perhaps you can specify the location of hibernate configuration file:

You can specify an absolute path, change the value of the HIBERNATE_CONFIG_FILE variable
Code:
public class SampleHibernateUtil {
    private static final SessionFactory sessionFactory;
    private static final String HIBERNATE_CONFIG_FILE = "hibernate.cfg.xml";

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
           
            sessionFactory = new AnnotationConfiguration().configure(
                    SampleHibernateUtil.class.getClassLoader().getResource(
                    HIBERNATE_CONFIG_FILE)
                    ).buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

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


Last edited by dppizza on Tue Feb 16, 2010 7:00 am, edited 1 time in total.

Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Mon Feb 15, 2010 8:22 am 
Newbie

Joined: Mon Jan 18, 2010 6:44 pm
Posts: 11
thanks for replay!!! :)

I change a class

Code:
package persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class SimpleHibernateUtil {
   private static final SessionFactory sessionFactory;
   private static final String HIBERNATE_CONFIG_FILE = "hibernate.cfg.xml";
   
   static {
      try {
         // Create the SessionFactory from standard (hibernate.cfg.xml)
         // config file.
         
         sessionFactory = new AnnotationConfiguration().configure(
            SimpleHibernateUtil.class.getClassLoader().getResource(
            HIBERNATE_CONFIG_FILE)
         ).buildSessionFactory();
      } catch (Throwable ex) {
         // Log the exception.
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
   }
   
   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
   
   public static void shutdown() {
      // Close caches and connection pools
      getSessionFactory().close();
   }
}


It says that import org.hibernate.cfg.AnnotationConfiguration; cannot be resloved, probably I missed to import some jar, but I don't know what???

For example import org.hibernate.cfg.Configuration; exists, but import org.hibernate.cfg.AnnotationConfiguration; it cannot find...

please help me :)


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Mon Feb 15, 2010 8:42 am 
Newbie

Joined: Mon Jan 18, 2010 6:44 pm
Posts: 11
One more try:

This iz my class, I change AnnotationConfiguration with Configuration

Code:
package persistence;

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

public class SimpleHibernateUtil {
   private static final SessionFactory sessionFactory;
   private static final String HIBERNATE_CONFIG_FILE = "hibernate.cfg.xml";
   
   static {
      try {
         // Create the SessionFactory from standard (hibernate.cfg.xml)
         // config file.
         
         sessionFactory = new Configuration().configure(
            SimpleHibernateUtil.class.getClassLoader().getResource(
            HIBERNATE_CONFIG_FILE)
         ).buildSessionFactory();
      } catch (Throwable ex) {
         // Log the exception.
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
   }
   
   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
   
   public static void shutdown() {
      // Close caches and connection pools
      getSessionFactory().close();
   }
}


But this part

SimpleHibernateUtil.class.getClassLoader().getResource(HIBERNATE_CONFIG_FILE)

returns null, where I made a mistake????


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Mon Feb 15, 2010 8:51 am 
Regular
Regular

Joined: Thu May 07, 2009 5:56 am
Posts: 94
Location: Toulouse, France
first, if you want to use AnnotationConfiguration put hibernate-annotations-3.4.0.jar in your classpath (see compatible matrix for you hibernate core jar at https://www.hibernate.org/30.html)

second, are you sure that your target copymetafiles works well? you can see hibernate.cfg.xml in your bin directory?
Have you tried to set configurationfile="hibernate.cfg.xml" (just file name, without /)?

_________________
everything should be made as simple as possible, but not simpler (AE)


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Mon Feb 15, 2010 5:23 pm 
Newbie

Joined: Mon Jan 18, 2010 6:44 pm
Posts: 11
First, thnx for reply! :)

first, if you want to use AnnotationConfiguration put hibernate-annotations-3.4.0.jar in your classpath (see compatible matrix for you hibernate core jar at https://www.hibernate.org/30.html)

-> I've add this jar, so now my class looks like this.. and there r no errors..

Code:
package persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class SimpleHibernateUtil {
   private static final SessionFactory sessionFactory;
   private static final String HIBERNATE_CONFIG_FILE = "hibernate.cfg.xml";
   
   static {
      try {
         // Create the SessionFactory from standard (hibernate.cfg.xml)
         // config file.
         
         sessionFactory = new AnnotationConfiguration().configure(
            SimpleHibernateUtil.class.getClassLoader().getResource(
            HIBERNATE_CONFIG_FILE)
         ).buildSessionFactory();
      } catch (Throwable ex) {
         // Log the exception.
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);
      }
   }
   
   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
   
   public static void shutdown() {
      // Close caches and connection pools
      getSessionFactory().close();
   }
}


And when I run HelloWorld.java I got these errors...

Code:
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager
Exception in thread "main" java.lang.ExceptionInInitializerError
   at persistence.SimpleHibernateUtil.<clinit>(Unknown Source)
   at hello.HelloWorld.main(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager
   ... 2 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.ReflectionManager
   at java.net.URLClassLoader$1.run(Unknown Source)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(Unknown Source)
   at java.lang.ClassLoader.loadClass(Unknown Source)
   at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
   at java.lang.ClassLoader.loadClass(Unknown Source)
   at java.lang.ClassLoader.loadClassInternal(Unknown Source)
   ... 2 more


what's wrong??

second, are you sure that your target copymetafiles works well? you can see hibernate.cfg.xml in your bin directory?

-> I don't know what r targer copymetafiles.. Can u explain me?? No, I can't se hibernate.cfg.xml in my bin directory.

Have you tried to set configurationfile="hibernate.cfg.xml" (just file name, without /)?

-> Where should I try this??

I know, it's borring, but please explain me with a little more details.. :)

thanx a lot!!!


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Mon Feb 15, 2010 11:41 pm 
Newbie

Joined: Sun Feb 14, 2010 8:08 am
Posts: 12
If I am correct, by saying "I've add this jar, so now my class looks like this.. and there r no errors.." means that you have added the hibernate-annotations-3.4.0.jar in your IDE (like say eclipse), and coming to running the HelloWorld.java, I hope you are using ant target for running it, the simple reason is during ant run it the hibernate-annotations-3.4.0.jar jar file is not in your classpath.

And for target's, that is an ant specific which if you are interested you can go through one simple tutorial at http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Tue Feb 16, 2010 5:53 am 
Regular
Regular

Joined: Thu May 07, 2009 5:56 am
Posts: 94
Location: Toulouse, France
to solve your classpath problems, you must add all required hibernate jars in your project (lib directory).
eg - if you are using hibernate core 3.3.x you also must add: hibernate-annotations-3.4.0.jar and hibernate-commons-annotations-3.1.0.jar. I suppose you've already added others needed jars found in lib/required directory of hibernate-distribution-3.3.2.GA archive. I used to search not found classes at http://www.findjar.com

now, let's return to initial problem, to create a database schema you not necessarily need to use Ant tasks. Set the property "hibernate.hbm2ddl.auto" (in hibernate.cfg.xml file). Valid values are: update, create and create-drop. Hibernate will create database schema when SessionFactory initializes. Afterwards, when you're get familiarized with Ant build, see http://docs.jboss.org/tools/3.0.0.GA/en ... ml#d0e2592

Hope I could help you!

_________________
everything should be made as simple as possible, but not simpler (AE)


Top
 Profile  
 
 Post subject: Re: How to generate data base schema?
PostPosted: Wed Feb 17, 2010 4:41 pm 
Newbie

Joined: Mon Jan 18, 2010 6:44 pm
Posts: 11
Hello,

U were right, I don't need ant al all, so for now I'm it's working without it.

Thnx to both of u for help!!!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.