How To Handle SQL Exceptions in JPA

Hi,
we are working on toplink JPA. My use case is I have an emp table with columns as "empid" , "emp name" , "job" with "empid" as primary Key. Here I'm creating a record in the Database by using a jspx page. Here My problem is when I'm entering a duplicate value for the empid I'm getting "ORA-00001: unique constraint (constraint_name) violated" . I'm able to catch the exception in the jspx backing bean where I'm calling the JPA insert method, But i could not catch the exception in the sessionEJB Bean. Is there any way to catch such exception in the sessionEJB.
could anyone help me out.
Thanks in Advance.
regards,
PrapanSol

You should be able to call flush on your EntityManager in your SessionBean to trigger the exception.
Note that the transaction will still be rolled back even if you catch this exception.

Similar Messages

  • How to handle sql exceptions properly

    Hi,
    Using Jdev 11.1.1.1.0 and JPA/Toplink
    Our application is used to modify a number of different tables. The tables are mapped in EJB entities and are exposed in session beans which calls the proper methods from the DAOs. We use ADF Rich components in our view project and we have a lot of validation for preventing primary key violations etc. But obviously we can't control everything and we need some exception handling. As it is now, if e.g an sql exception occurs, it will pop up a huge error dialog with the stack trace and the page rendering will fail etc and sometimes needs to restart.
    So, I'm not sure how to approach this. How do we catch these exceptions, notify the user, and stop the page rendering so that it doesn't completely shut down...I've searched around and found some useful information, but since we've never done this before it's a little hard to put things together. Could you please give me some easy examples for this?
    Thank you!
    André

    Hi, thanks for your reply.
    Yes, I have tried to override both getDisplayMessage and reportException. I now used the exact same code as in the example you referred to, and still I get the same result.
    So just to make it clear... If do an insert that causes integrity constraint violation, I get in my console:
    Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint violated
    Error Code: 1
    Call: INSERT INTO etc etc... When this happens, a huge popup appears in my page:
    javax.ejb.EJBException: BEA1-002236FD9E083057A4BD: weblogic.transaction.internal.AppSetRollbackOnlyException
         at weblogic.transaction.internal.TransactionImpl.setRollbackOnly(TransactionImpl.java:551)
         at weblogic.transaction.internal.TransactionManagerImpl.setRollbackOnly(TransactionManagerImpl.java:319)
         at weblogic.transaction.internal.TransactionManagerImpl.setRollbackOnly(TransactionManagerImpl.java:312)
         at org.eclipse.persistence.transaction.JTATransactionController.markTransactionForRollback_impl(JTATransactionController.java:145)
         at org.eclipse.persistence.transaction.AbstractTransactionController.markTransactionForRollback(AbstractTransactionController.java:196)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.rollbackTransaction(UnitOfWorkImpl.java:4486)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1351)
         at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:468)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1398)
         at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3022)
         at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:224)
         at ...................................etc etcThis is what I want to replace with an understandable message to the user. And this is what the custom error handler should do right?? There must be something I have misunderstood...

  • How To Handle SQL Exceptions in  Session EJB Bean

    Hi,
    we are working on toplink JPA. My use case is I have an emp table with columns as "empid" , "emp name" , "job" with "empid" as primary Key. Here I'm creating a record in the Database by using a jspx page. Here My problem is when I'm entering a duplicate value for the empid I'm getting "ORA-00001: unique constraint (constraint_name) violated" . I'm able to catch the exception in the jspx backing bean where I'm calling the JPA insert method, But i could not catch the exception in the sessionEJB Bean. Is there any way to catch such exception in the sessionEJB.
    could anyone help me out.
    Thanks in Advance.
    regards,
    PrapanSol

    You should be able to call flush on your EntityManager in your SessionBean to trigger the exception.
    Note that the transaction will still be rolled back even if you catch this exception.

  • How to handle the exception in GP(Exception : Activity could not be read)

    Hi all
    we are getting the GP exceptions  as  1) "Activity could not be read"  2) "Action has been stopped"
    3) error while processing the item can not be displayed
    Please let me know how to handle these exceptions in GP .
    currently i got some documents in SDN on GP exceptions but those are related to manual exceptions for example if you enterd wrong data in the inputfield then we can handle those exceptions then it will allow to enter the new value but the exceptions which i mentioned above are new it seems
    can you please let me know how to handle or solve those 3 exceptions
    Thanks
    bindu

    Hi Shikhil
    Thanks for your reply
    Please have a look below for exceptions which i am getting in GP and let me know how to handle these exceptions.
    1) "Activity could not be read"
    2) "Action has been stopped"
    3) error while processing the item can not be displayed
    if you give any idea/clue how to handle these exceptions then it would be great help to me
    Thanks
    Sunil

  • How to handle the Exception in GP using executable callabel object.

    Hi all,
            I handled an exception in GP using Background callable Object. That is working fine.
    (Ex: Exception_No_User_Found). The Problem is I am not able to handle the exceptions for normal callable object. I have done the same thing as i did in background callable object except implementing IGPBackgroundCallableObject Class.  I have created an WebDynpro DC Project where in getDescription method i declared an Exception and in execute method of component controller I caught the exception if no user found.
    Then i created an callable object for this simple DC project. but that is not working i could not catch the exception. when i execute the process it is asking the User ID if i give the wrong userId it is not refreshing back to the user id input form.
    But if i test that simple callable object separately it is throwing an Exception when I give the wrong input..
    but the same thing is working fine using background callable object.
    I couldn't handle the exception for the simple callable object or executable callable object.
    Please If anyone bring me the solution that would be appreciated.
    Thanks in advance.
    Regards,
    Malar.

    Hi Shikhil
    Thanks for your reply
    Please have a look below for exceptions which i am getting in GP and let me know how to handle these exceptions.
    1) "Activity could not be read"
    2) "Action has been stopped"
    3) error while processing the item can not be displayed
    if you give any idea/clue how to handle these exceptions then it would be great help to me
    Thanks
    Sunil

  • How to handle an Exception in GP through webdunpro

    Hi,
    How to handle exception in WebDynpro GP callable objects.
    I created exception parameter in getdescription() method like
    IGPExceptionInfo processExc1 = technicalDescription.addProcessException("USER_NOT_FOUND");
      processExc1.setNameKey("USER_KEY");
      processExc1.setDescriptionKey("USER_DESCRIPTION_KEY");
      processExc1.setFatal(true);
    In my Process I have 2 levels, In block level i am able to see the above created exception using exception tab.
    I have created an action with same callable object mapped, this action is mapped to exception handler & selected an repeat option from dropdown.
    If any exception occurs in execute method(like UMException) how to call an  handler from coding. I tried this code to call a handler
    String localizedMessage =textAccessor.getText("USER_NOT_FOUND");
      wdThis.wdFireEventTechnicalException(new GPTechnicalCallableObjectException(logger,localizedMessage,e));
    this is not working...
    Can any one please bring me an Solution.
    Thanks in advance.
    Regards
    ThenMalar

    Hi Shikhil
    Thanks for your reply
    Please have a look below for exceptions which i am getting in GP and let me know how to handle these exceptions.
    1) "Activity could not be read"
    2) "Action has been stopped"
    3) error while processing the item can not be displayed
    if you give any idea/clue how to handle these exceptions then it would be great help to me
    Thanks
    Sunil

  • How to handle XScript Exceptions ?? HELP !!

    hey buddies !!!
    I am getting the following exception in the browser for some jsp that is using XSCript.
    "Caught exception when evaluating expression "MIDC PHASE II DOMBIVALI {E}" with available binding contexts [actionForm, pageFlow, globalApp, request, session, appication, pageContext, bundle, container, url, pageInput]. Root cause: com.bea.wlw.netui.script.xscript.IllegalContextStateException: The context "E" could not be found. "
    Its okay that i am gettign this exception but i want to to know how to handle this exception. I tried using a try catch block but it didnot catch the exception and it still showed on the screen. I want to know how to handle this exception in the jsp ...
    Please help me ...thanks a lot !!!
    Nikhiol

    Nikhil--
    Can you paste in the tag (with the attributes) that is throwing the expression?
    Are you trying to data bind to "{E}"? If so, that's not a supported NetUI data binding context
    and the exception is legit. There isn't really a way to "handle" it -- it's more of a runtime error
    that occurs during regular development. When the application is deployed, such exceptions shouldn't
    occur.
    <g>
    Eddie
    Nikhil Gonsalves wrote:
    hey buddies !!!
    I am getting the following exception in the browser for some jsp that is using XSCript.
    "Caught exception when evaluating expression "MIDC PHASE II DOMBIVALI {E}" with available binding contexts [actionForm, pageFlow, globalApp, request, session, appication, pageContext, bundle, container, url, pageInput]. Root cause: com.bea.wlw.netui.script.xscript.IllegalContextStateException: The context "E" could not be found. "
    Its okay that i am gettign this exception but i want to to know how to handle this exception. I tried using a try catch block but it didnot catch the exception and it still showed on the screen. I want to know how to handle this exception in the jsp ...
    Please help me ...thanks a lot !!!
    Nikhiol

  • How to handle sql error exception in view object

    Guys,
             I have view object (with rows fetched from a sql query).
    Say the query in the VO looks like this..
    select plsql_fun(c) from dual
    (Note : the plsql function in the above query can throw an exception in some cases)
    when the plsql function throws a exception, we get sql exception  (oracle.jbo.SQLStmtException: JBO-27122: SQL error during statement preparation)
    Is there any way i can catch this exception and return -1 in the view object...
    Thanks in advance.

    Check out http://www.oracle.com/technetwork/issue-archive/2013/13-mar/o23adf-1897193.html
    Have you tried to surround hte executeQuery  with a try catch block?
    Timo

  • How to handle transaction exception

    Hi,
    I am using jdev 11g.
    I need to catch the exception in my transaction like (table not found, column must not be null, column not found, ...)
    hereunder is my code.
      public void saveOsaUser(OsaUser osaUser) throws Exception {
        EntityManager em = getEntityManager();
        try {
          utx.begin();
          em.joinTransaction();
          em.persist(osaUser);
          utx.commit();
        } catch (Exception ex) {
          try {
            utx.rollback();
            throw new Exception(ex.getLocalizedMessage());
          } catch (SQLException sqle) {
            throw new Exception(sqle.getLocalizedMessage());
          } catch (IllegalArgumentException iae) {
            throw new Exception(iae.getLocalizedMessage());
          } catch (EJBException ejbe) {
            throw new Exception(ejbe.getLocalizedMessage());
          } catch (RuntimeException re) {
            throw new Exception(re.getLocalizedMessage());
          } catch (Exception e) {
            throw new Exception(e.getLocalizedMessage());
        } finally {
          em.close();
      }Whatever the error type, i always get the message : Transaction does not exist.
    Kindly advice how can handle these SQL error (table not found, column must not be null, column not found, ...)
    Regards
    Emile BITAR

    Repost

  • How to handle multiple exception types in JSF 2?

    I'm trying to handle multiple exception types in JSF2, including a default error page for any unexpected exception types. The problems I'm having are:
    1) ViewExpiredException is handled only when no generic exception handler is specified
    2) "Regular" exceptions like NullPointerException are never handled
    My managed bean:
    @Named
    @SessionScoped
    public class MyController implements Serializable {
    /* A method that does nothing */
    public void doNothing() {
        //do nothing
    /* Generate a null pointer exception on purpose */
    public void generateNpe() throws NullPointerException {
        Object x = null;
        x.toString();
    My test page to generate the exception:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Test page</title>
    </h:head>
    <h:body>
        <h:form>
            <h:commandButton id="button1" value="do nothing" action="#{myController.doNothing}" />
            <h:commandButton id="button2" value="generate NPE" action="#{myController.generateNpe}" />
        </h:form>
    </h:body>
    </html>
    My web.xml:
    <!-- Redirect all NPEs to this page; this never works! -->
    <error-page>
        <exception-type>java.lang.NullPointerException</exception-type>
        <location>/error/error003.jsf</location>
    </error-page>
    <!-- Redirect all VEEs to this page; this works fine if the next section is excluded -->
    <error-page>
        <exception-type>javax.faces.application.ViewExpiredException</exception-type>
        <location>/error/error002.jsf</location>
    </error-page>
    <!-- This grabs everything, even with the previous sections defined.  If I exclude this error-page section, VEE works fine but NPE still does not get redirected -->
    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/error/error001.jsf</location>
    </error-page>My questions are as follows:
    1) How can we handle "regular" java exceptions like NPE?
    2) How can we define a catch-all for unexpected exception types, while still respecting specific exception handlers for VEE, etc?
    Thanks,
    Benjamin

    Is your data model right? If you are adding in one and deleting in another it sounds to me more like a process that an entity, in which case you may revisit your data model and simplify it, add in a session bean with the process method to co-ordinate between the two.
    However, if you want to map multiple different tables within a single entity bean it is possible and just part of the mapping. How you actualyl specify it depends on which implementation you are working with.
    Cheers,
    Peter.

  • How to handle system exception in Sync communication without BPM? Help!

    Hi Experts
       I have a Synchronous scenario in XI: webservice <------>RFC SAP R/3.
      Webservice is making a sync call to RFC FM in SAP R/3 system.
       I want to handle system exception when SAP R/3 is down and send an email alert.    
       Can I achieve this in graphical mapping without BPM? How? Kindly provide necessary steps/screenshots for the same.
       Are there any other alternatives for handling system exception apart from mapping and BPM?  
    Thanks
    Gopal

    Hi GopalKirshna,
          Yes,You can handle the Exception if at all you are using the RFC.You can achieve this without using BPM.
       Using Fault message you can catch the System Exception and even the primary role for Fault Message is to catch the RFC Exceptions.
       Please refer the Fault messages Notes to achieve this you will understand better.
    Hope I am clear.
    Please let me if you have any more queries regarding this..!
    Thanks and Rewards,
    Chandu.

  • How to handle multiple exceptions by the same code?

    Hi, all:
    In my situation I want AException and BException handled by the same code, while CException and DException handled by another code. How can I write my try-catch code in a simple way? Of course I can do the following:
    public void TheMainFunction() {
        try {
        } catch (AException e) {
            Handle_AB();
        } catch (BException e) {
            Handle_AB();
        } catch (CException e) {
            Handle_CD();
        } catch (DException e) {
            Handle_CD();
    private void Handle_AB() {
    private void Handle_CD() {
    }But is there a simpler way?
    Thanks in advance.

    If you have one or two places in your code that need multiple exceptions, just do it with multiple catch statements. Unless you are trying to write the most compact Programming 101 homework program, inventing tricks to remove two lines of code is not good use of your time.
    If you have multiple catches all over your code it could be a code smell. You may have too much stuff happening inside one try statement. It becomes hard to know what method call throws one of those exceptions, and you end up handling an exception from some else piece of code than what you intended. E.g. you mention NumberFormatException -- only process one user input inside that try/catch so it is easy to see what error message is given if that particular input is gunk. The next step of processing goes inside its own try/catch.
    In my case, the ArrayIndexOutOfBoundsException and
    NumberFormatException should be handled by the same way.Why?
    I don't think I have ever seen an ArrayIndexOutOfBoundsException that didn't indicate a bug in the code. Instead of an AIOOBE perhaps there should be an if statement somewhere that prevents it, or the algorithm logic should prevent it automatically.

  • How to handle JCO Exceptions at JCO (RFC) function call

    Hello Forum,
    I am implementing an JCO Server scenario.
    I use dynamic repositories like Example7.java from the JCO documentation.
    Example7 throws an JCO.AbapException if anything went wrong, e.g. the function is not implemented.
    How to react on this AbapException?
    The examples in SAP Help documentation only catch
    SYSTEM_FAILURE and COMMUNICATION_FAILURE.
    All other RFC modules I have seen which declare the function modules to be used by dynamic JCO repositories (like Example7.java) do not define any other Exception parameters.
    But these two are only thrown and caught when something with communication went completely wrong, e.g. RFC not found.
    But when RFC can be reached and the JCO Server is executing the Java method, an AbapException could be thrown on error. How to react on this?
    In my implementation based on the examples I always get a ABAP dump. The dump says:
    Exception named  without message text. Why that name?
    How to handle this type of exception in order to avoid the dump?
    Can anyone post an example please?
    Thanks,
    Carsten
    Edited by: Carsten Schön on Apr 15, 2008 4:22 PM
    Edited by: Carsten Schön on Apr 15, 2008 4:24 PM

    Hi Micky,
    thanks for your quick response.
    If so, to throw JCO.AbapException on JCO Server side is not correct?
    What I do is throwing the JCO.AbapException (like in the JCO Example 7).
    At the RFC call in APAB I handle both exceptions SYSTEM_FAILURE and COMMUNICATION_FAILURE like
    CALL FUNCTION 'MY_JCO_FUNCTION_MODULE'
        DESTINATION JCO_DEST
        <...>
        EXCEPTIONS
          SYSTEM_FAILURE        = 1  MESSAGE RFC_MESS
          COMMUNICATION_FAILURE = 2  MESSAGE RFC_MESS.
    This works as far something with RFC is wrong, e.g. Server can not find the function or Server not reachable.
    But the AbapException thrown by the JCO Server (Java) is not handled that way. Why?
    Sorry if this is the wrong forum but I tried posting in Netweaver integration and got no answer for 1 week and because it's ABAP related I thought the topic suites here.
    Carsten
    Edited by: Carsten Schön on Apr 15, 2008 5:10 PM

  • How to handle the exception com.sun.xml.internal.messaging.saaj.SOAPExcepn

    hi,
    I am accessing wsdl to get all the required data and the connection is establishing successfully thru java code but when i am calling the create user api the following exception is coming
    "com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: No NamespaceURI, SOAP requires faultcode content to be a QName"
    please tell me what is faultcode means and how to solve this exception

    Hi,
    Whenever there is any error inside the WebService or while it's processing ...it throws Exceptions ..We can handle these exception by our own to make the Exception details more readable.....For that we can create our own SOAPFault message...
    Please refer to the below Posts...
    1). If you are using JAXWS Style of WebService then : http://middlewaremagic.com/weblogic/?p=713
    2). If you are using JAXRPC Style of WebService then : http://middlewaremagic.com/weblogic/?p=721
    Thanks
    Jay SenSharma
    http://middlewaremagic.com/weblogic (Middleware magic Is Here)

  • How to handle SYSTEM_NO_MEMORY exception

    Hello,
    is there a way to handle the SYSTM_NO_MEMORY exception in a Z-Program? I want to show the user an error message with hints how to prevent this short dump instead of having the system showing the short dump.
    I tried to use TRY-statement but until now I wasn't successful.
    Thank you for your help,
    Stefan

    Hi Stefan;
    It seems there is no way to handle that exception as it's memory problem during run time.
    Please try to free unusable internal tables in each subroutine.
    Regards
    Vindy

Maybe you are looking for

  • Not able to compile servlet

    Hello I would like some one to help me. I have WindowsXp professional on my Laptop. I downloaded jdk and I am able to compile and run the core java files. I downloaded j2sdk1.4.2_10 from the website www.java.sun.com. and then set the path in the envi

  • Flash player update

    i repeatedly get the message that flash player may need to be updated evan after i update i still get the message and it will not let me do a google search.  This happens on my windows 7 pc and android.f

  • Disable sound in abap workbench?

    Hi, Is it posibble to disable sound in abap workbench when activating of generating an program? tnx, Adibo.

  • Colin: How do I open CS4 in 'The Levelater'?

    Hey Colin: I did as you suggested and I downloaded 'The levelater'. I grouped the same projects together again to create a new project just like the old one. I am anxious to see how it works. Also I was using a lot of memory doing it frame by frame a

  • Unmeasured Billing Analysis

    Hi.. What is the different between Volumetric Amount and Fixed Amount? How to find the Premise volumetric and fixed amount with respect to Posting date,Rate Category and Cal. Year/Quarter  Could you please proved is there any table or any transaction