-->
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.  [ 10 posts ] 
Author Message
 Post subject: Exception is not thrownwhen trying to create duplicate data.
PostPosted: Tue Jul 04, 2006 8:18 am 
Newbie

Joined: Tue Jul 04, 2006 7:36 am
Posts: 5
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp

Hibernate version:3.1.3

Mapping documents:<?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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@272.22.8.99:1521:std</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.username">user1</property>
<property name="hibernate.connection.password">password1</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.cglib.use_reflection_optimizer">false</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>




Code between sessionFactory.openSession() and session.close():Employee obj = new Employee();
obj.setEmployeeId(employeeId); // Duplicate EmployeeId
obj.setEmployeeName(employeeName);
obj.setDeptId(deptId);
obj.setDoj(doj);
obj.setDor(dor);

try
{
Session session = null;
Transaction transaction = null;
session = getCurrentSession();
session.save(obj);
}catch(HibernateException e)
{
System.out.println(" HIBERNATE EXCEPTION...");
}


Full stack trace of any exception that occurs:Exception is not thrown.

Name and version of the database you are using:Oracle
9.2.0.1.0


The generated SQL (show_sql=true):SQL is not generated in this case though it is set as true.

Debug level Hibernate log excerpt:
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>
  <class name="Employee" table="EMPLOYEE">
    <id name="employeeId" column="EMPLOYEE_ID" type="java.lang.Long">
    <generator class="assigned"/>
     </id>
    <property name="employeeName" column="EMPLOYEE_NAME" type="string" not-null="true"/>
    <property name="deptId" column="DEPT_ID" type="int" not-null="true"/>
    <property name="doj" column="DOJ" type="char" not-null="true"/>
    <property name="dor" column="DOR" type="java.lang.Long"/>
  </class>
</hibernate-mapping>
Quote:
For the above table there is a pojo class called employee. All the required value set into the pojo class.As per the above hibernate config file employee_id is assigned by the application.When I am trying to create Employee with duplicate employee_id, There is no exception thrown. Is there any configuration missed out or any specific property need to set to throw the exception in the above case.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 04, 2006 9:08 am 
Expert
Expert

Joined: Tue Dec 28, 2004 7:02 am
Posts: 573
Location: Toulouse, France
You don't seem to configure a transaction here, have you done it ? If not, that's completely normal : nothing goes to the database if you do not do your operations inside a transaction context, finishing with a commit.

http://www.hibernate.org/hib_docs/v3/re ... ersistence

You must do this :

Code:
        //open transaction
        session.beginTransaction();

        //do what you want with your data
        Event theEvent = new Event();
        theEvent.setTitle(title);
        theEvent.setDate(theDate);

        //ask to save it. At this moment, the object is stored in the Hibernate cache
        session.save(theEvent);
        //Try and push the data into the database. If OK, it is in, if not a rollback has to be done.
        session.getTransaction().commit();

_________________
Baptiste
PS : please don't forget to give credits below if you found this answer useful :)


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 04, 2006 9:56 am 
Newbie

Joined: Tue Jul 04, 2006 7:36 am
Posts: 5
I have started transaction in the client which call this create call. Below is the exact code:

Inside client

//open transaction
session.beginTransaction();
Employee obj = new Employee();
obj.setEmployeeId(employeeId); // Duplicate EmployeeId
obj.setEmployeeName(employeeName);
obj.setDeptId(deptId);
obj.setDoj(doj);
obj.setDor(dor);

//do what you want with your data
employeeDetails.create(obj);
try
{
Session session = null;
Transaction transaction = null;
session = getCurrentSession();
session.save(obj);
}catch(HibernateException e)
{
System.out.println(" HIBERNATE EXCEPTION...");
}
session.save(theEvent);
//Try and push the data into the database. If OK, it is in, if not a rollback has to be done.
session.getTransaction().commit();

Yet I didn't get any exception while trying to create duplicate data.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 04, 2006 10:28 am 
Expert
Expert

Joined: Tue Dec 28, 2004 7:02 am
Posts: 573
Location: Toulouse, France
I don't understand everything you're doing, but I just tried to store two entities with the same id, and it didn't work the second time...

The entity class :
Code:
public class Employee
{
   private String id;
   private String name;
   private String firstName;
   public Employee(String id, String name, String firstName)
   {
      this.id = id;
      this.name = name;
      this.firstName = firstName;
   }
        ...
   //getters and setters
}


The mapping :
Code:
<hibernate-mapping package="fr.mipih.duplicate">
   <class name="Employee">
      <id name="id">
         <generator class="assigned" />
      </id>
      <property name="name" />
      <property name="firstName" />
   </class>
</hibernate-mapping>


Then I did :
Code:
        public static void main(String[] args)
   {
      Session s = HibernateUtil.currentSession();
      s.beginTransaction();
      
      Employee e = new Employee("1","Bat","Mat");
      s.save(e);
      
      s.getTransaction().commit();
      s.close();

   }


If I call this code twice, I receive :
Code:
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
   at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
   at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
   at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
   at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:297)
   at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
   at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:988)
   at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:337)
   at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
   at fr.mipih.duplicate.TestDuplicate.main(TestDuplicate.java:21)
Caused by: java.sql.BatchUpdateException: failed batch
   at org.hsqldb.jdbc.jdbcStatement.executeBatch(Unknown Source)
   at org.hsqldb.jdbc.jdbcPreparedStatement.executeBatch(Unknown Source)
   at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)
   at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
   ... 8 more


So it works fine (obviously, because if not, I would be very concerned about the consistence of Oracle...).

You say you don't get any exception while trying to do that. So what is in your db after your calls finish ? Are you sure the exception is not thrown ? Maybe you simply redirected System.err somewhere you don't see inadvertently ?

_________________
Baptiste
PS : please don't forget to give credits below if you found this answer useful :)


Top
 Profile  
 
 Post subject: Exception is not thrownwhen trying to create duplicate data
PostPosted: Wed Jul 05, 2006 2:39 am 
Newbie

Joined: Tue Jul 04, 2006 7:36 am
Posts: 5
Thanks for your reply. Finally I got the same error in my application. But in this case, session.save(obj) method never throws any Exception (HibernateException). Is there any other way to catch this Exception and not to proceed with remaining operation once i get this Exception?


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 05, 2006 3:38 am 
Beginner
Beginner

Joined: Tue Jun 06, 2006 7:56 am
Posts: 20
Hi vanitha,

In Session.save(obj), you got a Hibernate Exception, I think the reason may be your Object is NULL.

Thanks
Edward


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 05, 2006 3:50 am 
Expert
Expert

Joined: Tue Dec 28, 2004 7:02 am
Posts: 573
Location: Toulouse, France
Actually, you don't have to catch any exception inside the transaction context.

In fact, you should rely on the thrown exception to know if you must rollback or not. So IMO you should proceed this way :

Session session = getSession();
Transaction tx = session.beginTransaction();
try
{
//do what you need
session.save(whatYouWant);

tx.commit();
}
catch(HibernateException e)
{
// you should even protect the rollback call with
// try catch and log it if you couldn't rollback
tx.rollback();
}

Instead of catching the exception around the save call and then trying to commit.

The thing to recall is to think about which exception you MUST catch. If you don't know what to do with an exception, then don't catch it. The worst thing is to catch it silently or just with a sysout as you did... Use a logging system, like log4j et really be careful about what you catch and what you don't.

_________________
Baptiste
PS : please don't forget to give credits below if you found this answer useful :)


Top
 Profile  
 
 Post subject: Exception is not thrownwhen trying to create duplicate data.
PostPosted: Wed Jul 05, 2006 4:36 am 
Newbie

Joined: Tue Jul 04, 2006 7:36 am
Posts: 5
I didn't get HibernateException in my application. In the sample session.save(obj) is not throwing any exception so the next consecutive process can not be stopped. After creating Employee, I am creating Employee account detail. In positive case there is no issue. But when Employee is not created b'coz of this unique key violation then the creation of employee account detail will be stopped. In this case there is a need to catch this kind of runtime exception and stop proceeding with next process. Is there a way to handle runtime issue in hibernate?


Top
 Profile  
 
 Post subject:
PostPosted: Wed Jul 12, 2006 3:12 am 
Beginner
Beginner

Joined: Tue Jun 06, 2006 7:56 am
Posts: 20
Hi,
In hbm.xml file, Check your id generator. And change native or increment, or assigned. I think it will works

Thanks
Edward


Top
 Profile  
 
 Post subject: Topic Reply Notification - Exception is not thrownwhen tryin
PostPosted: Wed Jul 12, 2006 3:16 am 
Newbie

Joined: Tue Jul 04, 2006 7:36 am
Posts: 5
As per the sample id has Assigned generator. Though the runtime issue is not handled in code.

Regards,
Vanitha


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