-->
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.  [ 3 posts ] 
Author Message
 Post subject: Sample code is not executing though Ant Script.
PostPosted: Tue Aug 24, 2010 7:42 am 
Newbie

Joined: Tue Aug 24, 2010 5:43 am
Posts: 3
Hello,

I am new into the Hiberanate development and this is my 1st application with Hibenate/MySql/Ant.
I am refrring the Hibernate manning book as a reference material.

I developed a sample application and its running correctly if i execute it from eclipse, but it gets failed when i tried to excute it from Ant. (Its giving error - /hibernate.cfg.xml not found)

Directory Structure -
src\com\manning\hq\ch04
Address.java
Event.java
EventLoader.java
HibernateFactory.java
Location.java
Event.hbm.xml
Location.hbm.xml
log4j.properties

In src folder all these 3 files are placed -
hibernate.cfg.xml
hibernate-build.xml
build4.xml

When i run EventLoader.java from eclipse , it is working correctlya and a new row/entry gats created in DB/tables.
But while executing from build4.xml file i am getting following trace -
Code:
     [java] Aug 24, 2010 4:53:40 PM org.hibernate.cfg.Environment <clinit>
     [java] INFO: Hibernate 3.2.1
     [java] Aug 24, 2010 4:53:40 PM org.hibernate.cfg.Environment <clinit>
     [java] INFO: hibernate.properties not found
     [java] Aug 24, 2010 4:53:40 PM org.hibernate.cfg.Environment buildBytecodeProvider
     [java] INFO: Bytecode provider name : cglib
     [java] Aug 24, 2010 4:53:40 PM org.hibernate.cfg.Environment <clinit>
     [java] INFO: using JDK 1.4 java.sql.Timestamp handling
     [java] Aug 24, 2010 4:53:40 PM org.hibernate.cfg.Configuration configure
     [java] INFO: configuring from resource: /hibernate.cfg.xml
     [java] Aug 24, 2010 4:53:40 PM org.hibernate.cfg.Configuration getConfigurationInputStream
     [java] INFO: Configuration resource: /hibernate.cfg.xml
     [java] org.hibernate.HibernateException: /hibernate.cfg.xml not found
     [java]    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
     [java]    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1402)
     [java]    at org.hibernate.cfg.Configuration.configure(Configuration.java:1424)
     [java]    at org.hibernate.cfg.Configuration.configure(Configuration.java:1411)
     [java]    at com.manning.hq.ch04.HibernateFactory.buildSessionFactory(Unknown Source)
     [java]    at com.manning.hq.ch04.EventLoader.main(Unknown Source)
     [java]    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
     [java]    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
     [java]    at java.lang.reflect.Method.invoke(Unknown Source)
     [java]    at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
     [java]    at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
     [java]    at org.apache.tools.ant.taskdefs.Java.run(Java.java:764)
     [java]    at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:218)
     [java]    at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:132)
     [java]    at org.apache.tools.ant.taskdefs.Java.execute(Java.java:105)
     [java]    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
     [java]    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
     [java]    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
     [java]    at java.lang.reflect.Method.invoke(Unknown Source)
     [java]    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
     [java]    at org.apache.tools.ant.Task.perform(Task.java:348)
     [java]    at org.apache.tools.ant.Target.execute(Target.java:357)
     [java]    at org.apache.tools.ant.Target.performTasks(Target.java:385)
     [java]    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
     [java]    at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
     [java]    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
     [java]    at org.eclipse.ant.internal.ui.antsupport.EclipseDefaultExecutor.executeTargets(EclipseDefaultExecutor.java:32)
     [java]    at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
     [java]    at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.run(InternalAntRunner.java:423)
     [java]    at org.eclipse.ant.internal.ui.antsupport.InternalAntRunner.main(InternalAntRunner.java:137)



Below are my src file codes -
hibernate.cfg.xml
Code:
<?xml version="1.0"?>
<!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.username">root</property>
      <property name="connection.password">root</property>
      <property name="connection.url">
         jdbc:mysql://localhost/hbmdb
      </property>
      <property name="connection.driver_class">
         com.mysql.jdbc.Driver
      </property>
      <property name="dialect">
         org.hibernate.dialect.MySQLDialect
      </property>
   
      <mapping resource="com/manning/hq/ch04/Event.hbm.xml"/>
      <mapping resource="com/manning/hq/ch04/Location.hbm.xml"/>
   </session-factory>
</hibernate-configuration>



hibernate-build.xml
Code:
<?xml version="1.0"?>
<project name="hibernate-build" default="schema-export">
   <property name="src.java.dir" value="com/manning/hq/ch04"/>
   <property name="build.classes.dir" value="build/classes"/>
   <property name="hibernate.lib.dir" value="D:/Sharad/Personal/Java docs - new/Hibnernate/lib"/>
   <property name="hibernate.cfg.xml.file" value="hibernate.cfg.xml"/>
   
   <path id="project.classpath">
      <pathelement location="${build.classes.dir}"/>
   </path>
   
   <path id="hibernate.lib.path">
      <fileset dir="${hibernate.lib.dir}">
         <include name="**/*.jar"/>
      </fileset>
   </path>
   
   <path id="Config.XML.classpath">
      <pathelement location="${hibernate.cfg.xml.file}"/>
   </path>
   
   <path id="runtime.classpath">
      <path refid="project.classpath"/>
      <path refid="hibernate.lib.path"/>
      <path refid="Config.XML.classpath"/>
   </path>

   <target name="schema-export">
      <taskdef name="schemaexport" classname="org.hibernate.tool.hbm2ddl.SchemaExportTask">
         <classpath refid="runtime.classpath" />
      </taskdef>
      
      <echo>started</echo>
      <schemaexport config="${hibernate.cfg.xml.file}"/>
      <echo>file schema export job done</echo>
   </target>

</project>


build4.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<project name="build4.xml" default="build">

   <import file="hibernate-build.xml" />

   <target name="clean">
      <delete dir="${build.classes.dir}"/>
   </target>
   <target name="init" depends="clean" >
      <mkdir dir="${build.classes.dir}"/>
   </target>
   <target name="compile" depends="init" >
      <javac
         srcdir="${src.java.dir}"
         destdir="${build.classes.dir}">
         <classpath refid="hibernate.lib.path"/>
      </javac>
   </target>
   
   <target name="build" depends="compile">
      <java classname="com.manning.hq.ch04.EventLoader">
         <classpath refid="runtime.classpath"/>
      </java>
   </target>

   <target name="schema-export" depends="compile,hibernate-build.schema-export"/>   
</project>


Address.java
Code:
package com.manning.hq.ch04;

public class Address
{
   private String streetAddress;
   private String city;
   private String state;
   private String zipCode;
   
   public String getStreetAddress() { return streetAddress; }
   public void setStreetAddress(String streetAddress)
   {
      this.streetAddress = streetAddress;
   }
   public String getCity() { return city; }
   public void setCity(String city)
   {
      this.city = city;
   }
   public String getState() { return state; }
   public void setState(String state)
   {
      this.state = state;
   }
   public String getZipCode() { return zipCode; }
   public void setZipCode(String zipCode)
   {
      this.zipCode = zipCode;
   }
}



Event.hbm.xml
Code:
<?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 package="com.manning.hq.ch04">
   <class name="Event" table="events">
      <id name="id" column="uid" type="long">
         <generator class="native"/>
      </id>
      <property name="name" type="string"/>
      <property name="startDate" column="start_date" type="date"/>
      <property name="duration" type="integer"/>
      <many-to-one name="location" column="location_id" class="Location" cascade="save-update"/>
   </class>
</hibernate-mapping>



Event.java
Code:
package com.manning.hq.ch04;

import java.io.Serializable;
import java.util.Date;
public class Event implements Serializable
{
   private Long id;
   private int duration;
   private String name;
   private Date startDate;
   private Location location;
   
   public Event() { }
   public Event(String name) {
      this.name = name;
   }
   public Long getId() { return id; }
   public void setId(Long id) {
      this.id = id;
   }
   public String getName() { return name; }
   public void setName(String name) {
      this.name = name;
   }
   public Date getStartDate() { return startDate; }
   public void setStartDate(Date startDate) {
      this.startDate = startDate;
   }
   public int getDuration() { return duration; }
   public void setDuration(int duration) {
      this.duration = duration;
   }
   public Location getLocation() { return location; }
   public void setLocation(Location location) {
      this.location = location;
   }
}


EventLoader.java
Code:
package com.manning.hq.ch04;

import java.util.Calendar;
import java.util.Date;

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

public class EventLoader
{
   public static void main(String[] args)
   {
      Location location = new Location();
      location.setName("Hilton Convention Center");
      location.getAddress().setStreetAddress("950 North Stafford St.");
      location.getAddress().setCity("Arlington");
      location.getAddress().setState("VA");
      location.getAddress().setZipCode("22204");

      Event event = new Event();
      event.setName("Annual Meeting");
      event.setDuration(60);
      event.setStartDate(createDate(2004, 11, 1));
      event.setLocation(location);
      
      Session session = null;
      Transaction tx = null;
      try
      {
         HibernateFactory.buildSessionFactory();
         session = HibernateFactory.openSession();
         tx = session.beginTransaction();

         session.save(event);
         System.out.println("==============="+event.getId());
         //session.save(location); // using cascade in Event.hbm.xml      
         tx.commit();
         System.out.println("Event and location saved!");
      } catch (HibernateException e)
      {
         e.printStackTrace();
         HibernateFactory.rollback(tx);
         //throw e; // Rethrow
      } finally
      {
         HibernateFactory.close(session);
         HibernateFactory.closeFactory();
      }
   }
   
   /**
   * @param year
   * @param month - This is 0-based:
   * 0 = January, 11 = December
   * @param day
   * @return
   */
   private static Date createDate(int year, int month, int day)
   {
      Calendar calendar = Calendar.getInstance();
      calendar.set(year, month, day);
      return calendar.getTime();
   }
}


HibernateFactory.java
Code:
package com.manning.hq.ch04;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

public class HibernateFactory
{
   private static SessionFactory sessionFactory;
   private static Log log = LogFactory.getLog(HibernateFactory.class);
   public static SessionFactory buildSessionFactory() throws HibernateException
   {
      if(sessionFactory != null){
         closeFactory();
      }
      Configuration configuration = new Configuration();
      configuration.configure();
      sessionFactory = configuration.buildSessionFactory();
      log.info("=========Session factory Created ");
      return sessionFactory;
   }
   public static SessionFactory getSessionFactory() {
      return sessionFactory;
   }
   public static Session openSession() throws HibernateException {
      return sessionFactory.openSession();
   }
   public static void closeFactory()
   {
      if (sessionFactory != null)
      {
         try
         {
            sessionFactory.close();
         } catch (HibernateException ignored)
         {
            log.error("Couldn't close SessionFactory", ignored);
         }
      }
   }
   public static void close(Session session)
   {
      if (session != null)
      {
         try
         {
            session.close();
         } catch (HibernateException ignored) {
            log.error("Couldn't close Session", ignored);
         }
      }
   }
   public static void rollback(Transaction tx)
   {
      try
      {
         if (tx != null)
         {
            tx.rollback();
         }
      } catch (HibernateException ignored)
      {
         log.error("Couldn't rollback Transaction", ignored);
      }
   }
}



Location.hbm.xml
Code:
<?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 package="com.manning.hq.ch04">
   <class name="Location" table="locations">
      <id name="id" column="uid" type="long">
         <generator class="native"/>
      </id>
      <property name="name" type="string"/>
      
      <component name="address" class="Address">
         <property name="streetAddress" column="street_address" type="string"/>
         <property name="city" type="string"/>
         <property name="state" type="string"/>
         <property name="zipCode" column="zip_code" type="string"/>
      </component>
   </class>
</hibernate-mapping>


Location.java
Code:
package com.manning.hq.ch04;

//package com.manning.hq.ch04;
import java.io.Serializable;
public class Location implements Serializable
{
   private Long id;
   private String name;
   //private String address;
   private Address address = new Address();
   
   public Address getAddress() {
      return address;
   }
   public void setAddress(Address address) {
      this.address = address;
   }
   private String streetAddress;
   public String getStreetAddress() {
      return streetAddress;
   }
   public void setStreetAddress(String streetAddress) {
      this.streetAddress = streetAddress;
   }
   public String getCity() {
      return city;
   }
   public void setCity(String city) {
      this.city = city;
   }
   public String getState() {
      return state;
   }
   public void setState(String state) {
      this.state = state;
   }
   public String getZipCode() {
      return zipCode;
   }
   public void setZipCode(String zipCode) {
      this.zipCode = zipCode;
   }
   private String city;
   private String state;
   private String zipCode;
   
   public Location() { }
   public Location(String name) {
      this.name = name;
   }
   public Long getId() { return id; }
   public void setId(Long id) {
      this.id = id;
   }
   public String getName() { return name; }
   public void setName(String name) {
      this.name = name;
   }
   /*public String getAddress() { return address; }
   public void setAddress(String address) {
      this.address = address;
   }*/
}



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 %5p %c{1}:%m%n
### set log levels - for more verbose logging change
### 'info' to 'debug'
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=warn


I believe, i had did something wrong in ant scripting but not able to figure it out.
Please help me in resolving this.


Also when i default="schema-export" in build4.xml and run it i m getting following error.
Code:
BUILD FAILED
D:\WorkSpaceJ2EE_35SR2\Hibernate_Manning\src\hibernate-build.xml:34: java.lang.ExceptionInInitializerError


It doesn't give any other information, so not able to predict what/where went anything wrong.


Thanks in Advance
Sharad


Top
 Profile  
 
 Post subject: Re: Sample code is not executing though Ant Script.
PostPosted: Tue Aug 24, 2010 8:06 am 
Newbie

Joined: Tue Aug 24, 2010 5:43 am
Posts: 3
I am using following list of jars.
org.apache.commons.logging_1.0.4.v200706111724.jar
commons-collections-3.1.jar
javaee.jar
hibernate3.jar
dom4j-1.6.1.jar
cglib-nodep-2.2.jar
mysql-connector-java-5.1.13-bin.jar


Thanks
Sharad


Top
 Profile  
 
 Post subject: Re: Sample code is not executing though Ant Script.
PostPosted: Tue Aug 24, 2010 11:01 am 
Newbie

Joined: Tue Aug 24, 2010 5:43 am
Posts: 3
Hello another update.
After working on ANT script, i am able to execute the program and Entries are made in database tables succesfully.

But still i am facing the 2nd problem, i.e. running hibernate-build.xml to clean up schema related tasks (droping and recreating tables)
error is -

BUILD FAILED
D:\WorkSpaceJ2EE_35SR2\Hibernate_Manning\src\hibernate-build.xml:30: java.lang.ExceptionInInitializerError

Please let me knnow how to resolve this.

Thanks
Sharad


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 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.