-->
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.  [ 2 posts ] 
Author Message
 Post subject: Error while inserting a row with duplicate Primary key
PostPosted: Tue Jul 03, 2007 11:24 am 
Newbie

Joined: Mon May 28, 2007 6:24 am
Posts: 11
Location: Bangalore
Scenario

My program is a Simple Swing program which asks the user to input a Message ID and a Message Text to store in a Mesage table which is created by hibernate itself. It works perfect as long as the user enters different message ids. But it crashes when the user enters a duplicate Message id as its a primary key. How do I catch the exception showing a Joptionpane information warning message and exit the program

Hibernate version: 3.2.4

Mapping documents

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="hibernate.Message" table="message">
   <id name="id" column="id" >
   <generator class="assigned"/>
  </id>

  <property name="text" column ="text" />
 
</class>
</hibernate-mapping>


Code


Code:
package hibernate;

import javax.swing.JOptionPane;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException;

public class MessageAppln {
   public static void main(String[] args) {
       Session session = null;
       Transaction tx = null;
       Message message = null;
       String choice = null;
       int count = 0;
       try{
          SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
          session =sessionFactory.openSession();
          do{
             choice = JOptionPane.showInputDialog(null, "Do you want to Insert into Message Table (Y/N)");
             if (choice.equalsIgnoreCase("Y")){
                String messageId = JOptionPane.showInputDialog(null, "Enter the Message ID (Number)");
                int id = Integer.parseInt(messageId);
                String text = JOptionPane.showInputDialog(null, "Enter the Message text");   
                tx = session.beginTransaction();
                message = new Message();
                  message.setId(id);
                  message.setText(text);
                  session.save(message);
                  tx.commit();
                  count++;
             }
          }while (!choice.equalsIgnoreCase("N"));
         
           System.out.println(count+ " Row(s) inserted into the Message Table");
          
       }catch(NumberFormatException e){
          e.printStackTrace();
       }catch(HibernateException e){
          System.out.println("Entered Duplicate Message id : "+message.getId());
          JOptionPane.showMessageDialog(null, "Entered Duplicate Message id : "+message.getId());
          e.printStackTrace();
       }
       catch(Exception e){
          e.printStackTrace();
       }finally{
          session.flush();
          session.close();
          System.exit(0);
       }
   }
}




Full stack trace of any exception that occurs:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
1 Row(s) inserted into the Message Table
Hibernate: insert into message (text, id) values (?, ?)
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at hibernate.MessageAppln.main(MessageAppln.java:49)
Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (SCOTT.SYS_C002744) violated

at oracle.jdbc.dbaccess.DBError.throwBatchUpdateException(DBError.java:441)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:3377)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
... 6 more


Name and version of the database you are using:

Oracle 9i

Configuration File

Code:
<?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.url">jdbc:oracle:thin:@localhost:1521:bob</property>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.username">scott</property>
        <property name="hibernate.connection.password">tiger</property>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
      <property name="show_sql">true</property>
      <property name="hibernate.hbm2ddl.auto">update</property>

        <mapping resource="Message.hbm.xml" />

      </session-factory>
</hibernate-configuration>

_________________
http://www.hibernate-tutorial.com
http://www.spring-hibernate.com
http://www.spring-tutorial.com


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jul 03, 2007 2:08 pm 
Newbie

Joined: Mon May 28, 2007 6:24 am
Posts: 11
Location: Bangalore
I have edited the above Source code now. The program behaves better by not allowing the users to add duplicate rows. But an attempt to inserting a duplicate message id should go to the Hibernate exception catch block and open up the Warning JOptionPane and print a error message to console but this does not happen. Why is it so.

_________________
http://www.hibernate-tutorial.com
http://www.spring-hibernate.com
http://www.spring-tutorial.com


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