How to catch SQLException in CMP bean

Hi there,
I am using CMP beans to set columns, one of which has referential integrity.
Because the abstract set() method does not declare to throw SQLException, I
can not catch SQLException in my session bean (which calls local CMP bean
for creating and setting entity beans), the compiler complains "unreachable
block".
I can only try catching RemoteException in my delegate class. I do not like
that, I even tried to catch all exceptions, i.e., catch Exception, in my
session bean, I still did not catch the SQLException.
The update calls are made into DB probably right before the transaction
completes, however, since it is the container generated classes that does DB
calls and throw SQLException, I could not catch it there since I do not have
the source code for generated classes.
Call stack is attached.
Any suggestion is welcome. Basically I would like to catch SQLException in
session bean.
Thanks.
Yan
<Oct 18, 2004 10:09:06 AM EDT> <Error> <EJB> <BEA-010026> <Exception
occurred during commit of transaction Name=[EJB com.med
lus.serviceHub.rx.ejb.pharmacy.PharmacyMgrSession.updatePharmacy(java.util.A
rrayList,long,java.lang.String)],Xid=BEA1-0153A4
2892EE25246C3(29499284),Status=Rolled back.
[Reason=weblogic.utils.NestedRuntimeException: Error writing from
beforeCompleti
n - with nested exception:
[java.sql.SQLException: ORA-02291: integrity constraint
(DX_OWNER.STATEABBR_RXPHARM_FK) violated - parent key not found
]],numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds since begin=0,seconds
left=30,XAServerResourceInfo[weblogic.jdbc.wrappe
.JTSXAResourceImpl]=(ServerResourceInfo[weblogic.jdbc.wrapper.JTSXAResourceI
mpl]=(state=rolledback,assigned=myserver),xar=we
logic.jdbc.wrapper.JTSXAResourceImpl@1a7491e,re-Registered =
false),SCInfo[hubservices+myserver]=(state=rolledback),properti
s=({weblogic.transaction.name=[EJB
com.medplus.serviceHub.rx.ejb.pharmacy.PharmacyMgrSession.updatePharmacy(jav
a.util.ArrayL
st,long,java.lang.String)], weblogic.jdbc=t3://172.18.15.54:7001}),local
properties=({modifiedListeners=[weblogic.ejb20.inte
nal.TxManager$TxListener@71de6e]}),OwnerTransactionManager=ServerTM[ServerCo
ordinatorDescriptor=(CoordinatorURL=myserver+172
18.15.54:7001+hubservices+t3+,
XAResources={},NonXAResources={})],CoordinatorURL=myserver+172.18.15.54:7001
hubservicest3+)
java.sql.SQLException: ORA-02291: integrity constraint
(DX_OWNER.STATEABBR_RXPHARM_FK) violated - parent key not found
at
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
at
oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:18
1)
at
oracle.jdbc.driver.T4CPreparedStatement.execute_for_rows(T4CPreparedStatemen
t.java:543)
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java
:1027)
at
oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedSta
tement.java:2885)
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedState
ment.java:2957)
at
weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java
:115)
at
com.medplus.serviceHub.rx.ejb.pharmacy.Pharmacy_i7s2ww__WebLogic_CMP_RDBMS._
WLstore(Pharmacy_i7s2ww__WebLogic_C
P_RDBMS.java:3564)
at
com.medplus.serviceHub.rx.ejb.pharmacy.Pharmacy_i7s2ww__WebLogic_CMP_RDBMS.e
jbStore(Pharmacy_i7s2ww__WebLogic_CMP
RDBMS.java:3390)
at
weblogic.ejb20.manager.DBManager.beforeCompletion(DBManager.java:965)
at
weblogic.ejb20.internal.TxManager$TxListener.beforeCompletion(TxManager.java
:653)
at
weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInf
o.java:1010)
at
weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCI
nfo.java:115)
at
weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(
ServerTransactionImpl.java:1184)
at
weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerT
ransactionImpl.java:1910)
at
weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTra
nsactionImpl.java:273)
at
weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransaction
Impl.java:244)
at
weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:299)
at
weblogic.ejb20.internal.StatelessEJBObject.postInvoke(StatelessEJBObject.jav
a:140)
at
com.medplus.serviceHub.rx.ejb.pharmacy.PharmacyMgr_kb6mwa_EOImpl.updatePharm
acy(PharmacyMgr_kb6mwa_EOImpl.java:16
at
com.medplus.serviceHub.rx.ejb.pharmacy.PharmacyMgr_kb6mwa_EOImpl_WLSkel.invo
ke(Unknown Source)
at
weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:477)
at
weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java
:108)
at
weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:420)
at
weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubjec
t.java:363)
at
weblogic.security.service.SecurityManager.runAs(SecurityManager.java:144)
at
weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:415)
at
weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:3
0)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
--------------- nested within: ------------------

Hi there,
I am using CMP beans to set columns, one of which has referential integrity.
Because the abstract set() method does not declare to throw SQLException, I
can not catch SQLException in my session bean (which calls local CMP bean
for creating and setting entity beans), the compiler complains "unreachable
block".
I can only try catching RemoteException in my delegate class. I do not like
that, I even tried to catch all exceptions, i.e., catch Exception, in my
session bean, I still did not catch the SQLException.
The update calls are made into DB probably right before the transaction
completes, however, since it is the container generated classes that does DB
calls and throw SQLException, I could not catch it there since I do not have
the source code for generated classes.
Call stack is attached.
Any suggestion is welcome. Basically I would like to catch SQLException in
session bean.
Thanks.
Yan
<Oct 18, 2004 10:09:06 AM EDT> <Error> <EJB> <BEA-010026> <Exception
occurred during commit of transaction Name=[EJB com.med
lus.serviceHub.rx.ejb.pharmacy.PharmacyMgrSession.updatePharmacy(java.util.A
rrayList,long,java.lang.String)],Xid=BEA1-0153A4
2892EE25246C3(29499284),Status=Rolled back.
[Reason=weblogic.utils.NestedRuntimeException: Error writing from
beforeCompleti
n - with nested exception:
[java.sql.SQLException: ORA-02291: integrity constraint
(DX_OWNER.STATEABBR_RXPHARM_FK) violated - parent key not found
]],numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds since begin=0,seconds
left=30,XAServerResourceInfo[weblogic.jdbc.wrappe
.JTSXAResourceImpl]=(ServerResourceInfo[weblogic.jdbc.wrapper.JTSXAResourceI
mpl]=(state=rolledback,assigned=myserver),xar=we
logic.jdbc.wrapper.JTSXAResourceImpl@1a7491e,re-Registered =
false),SCInfo[hubservices+myserver]=(state=rolledback),properti
s=({weblogic.transaction.name=[EJB
com.medplus.serviceHub.rx.ejb.pharmacy.PharmacyMgrSession.updatePharmacy(jav
a.util.ArrayL
st,long,java.lang.String)], weblogic.jdbc=t3://172.18.15.54:7001}),local
properties=({modifiedListeners=[weblogic.ejb20.inte
nal.TxManager$TxListener@71de6e]}),OwnerTransactionManager=ServerTM[ServerCo
ordinatorDescriptor=(CoordinatorURL=myserver+172
18.15.54:7001+hubservices+t3+,
XAResources={},NonXAResources={})],CoordinatorURL=myserver+172.18.15.54:7001
hubservicest3+)
java.sql.SQLException: ORA-02291: integrity constraint
(DX_OWNER.STATEABBR_RXPHARM_FK) violated - parent key not found
at
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
at
oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:18
1)
at
oracle.jdbc.driver.T4CPreparedStatement.execute_for_rows(T4CPreparedStatemen
t.java:543)
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java
:1027)
at
oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedSta
tement.java:2885)
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedState
ment.java:2957)
at
weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java
:115)
at
com.medplus.serviceHub.rx.ejb.pharmacy.Pharmacy_i7s2ww__WebLogic_CMP_RDBMS._
WLstore(Pharmacy_i7s2ww__WebLogic_C
P_RDBMS.java:3564)
at
com.medplus.serviceHub.rx.ejb.pharmacy.Pharmacy_i7s2ww__WebLogic_CMP_RDBMS.e
jbStore(Pharmacy_i7s2ww__WebLogic_CMP
RDBMS.java:3390)
at
weblogic.ejb20.manager.DBManager.beforeCompletion(DBManager.java:965)
at
weblogic.ejb20.internal.TxManager$TxListener.beforeCompletion(TxManager.java
:653)
at
weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInf
o.java:1010)
at
weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCI
nfo.java:115)
at
weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(
ServerTransactionImpl.java:1184)
at
weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerT
ransactionImpl.java:1910)
at
weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTra
nsactionImpl.java:273)
at
weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransaction
Impl.java:244)
at
weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:299)
at
weblogic.ejb20.internal.StatelessEJBObject.postInvoke(StatelessEJBObject.jav
a:140)
at
com.medplus.serviceHub.rx.ejb.pharmacy.PharmacyMgr_kb6mwa_EOImpl.updatePharm
acy(PharmacyMgr_kb6mwa_EOImpl.java:16
at
com.medplus.serviceHub.rx.ejb.pharmacy.PharmacyMgr_kb6mwa_EOImpl_WLSkel.invo
ke(Unknown Source)
at
weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:477)
at
weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java
:108)
at
weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:420)
at
weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubjec
t.java:363)
at
weblogic.security.service.SecurityManager.runAs(SecurityManager.java:144)
at
weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:415)
at
weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:3
0)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
--------------- nested within: ------------------

Similar Messages

  • OC4J 10.1.3: EJB3 - How to catch SQLExceptions in a SessionBean

    Hi,
    originally I posted this a few minutes ago in the toplink forum, but I'm
    unsure if this better suits here. So exceptionally, I post it here as well with a
    reference to:
    EJB3 - How to catch SQLExceptions from within a stateful session bean
    I would like to catch any exception while persisisting the data right in my stateful
    session bean and don't have to wait until the client receives an SQLException
    wrapped in a bunch of other exceptions.
    Here some code fragments to illustrate my problem:
    // in Client:
    InitialContext ctx = new InitialContext();
    statefulWork =  (StatefulWork) ctx.lookup("StatefulWork");
    try {
      statefulWork.doIt();
    } catch (Throwable t) {
      // don't want to implement db-failover here, even though this works
    // in SSB
    @Resource
    private EntityManager em;
    public void doIt() {
            try {
                // create some entites here, do some loops, long running transaction
                em.persist(oneOfMyEntityObjects);
                // set some state in the SSB here
            } catch (Throwable t) {
                // I want to catch all exceptions the persistence provider (toplink) gets
                // but I don't get any here :-(
                // this should be to implement proper retry after reconnect (RAC with TAF)
    }In my testcase I issue a shutdown abort while insert statements are executed.
    The client receives an EJBException, but within the SSB nothing...
    How to change this behavior?
    Here is what one can find in the OC4J log:
    [TopLink Warnung]: 2006.03.27 03:25:32.220--UnitOfWork(13386)--Thread(Thread[RMICallHandler-0,5,RequestThreadGroup])--Exception [TOPLINK-4002] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.DatabaseException
    Interne Exception: java.sql.SQLException: ORA-25402: transaction must roll back
    Fehlercode:25402
    Call:INSERT INTO T_RUN_DETAILS (ID, INS_TIME, COUNTER, RUN_ID) VALUES (105781, '2006.03.27 03:23:55', 450, 801)After that the transaction is properly rolled back (automatically) and the client
    could implement the failover code, but I could not find a possibility to control this
    at server side. Even with BMT I could not manage to catch this exception. I
    wouldn't have a problem if I had to call ctx.setRollbackOnly() myself.
    Hope someone can help. I'm getting a little desperate here.
    Thanks,
    Eric

    Thanks to the help of James Sutherland I managed to get this working.
    I had to add a call to em.flush() and use BMT for the SSB. For details please follow my link to the toplink-forum!
    James thinks OC4J can handle automatic transaction retries but wasn't sure about how to configure this in OC4J. Anyone can help?
    Regards,
    Eric

  • HOW TO GET THE SQLEXCEPTION FROM CMP BEAN

    Hi All,
    I am using CMP Bean as back end in my application.My client class access the CMP Bean to Create or Update the records via Session Facade.In My Database i am using trigger to avoid the concurrent updation.So when the concurrent calls made the database triigger will throw ERROR ..It works fine....But in EJB all the Exception will be thrown as RemoteException.
    But my problem is container will always throws Remote Exception to the client .I need get the actual SQL EXCEPTION (SQL STATE)thrown from the database.I have used the printStackTrace() method to print it in my Console..It work fine..I need to covert this as String ..So that only i can compare the String and can tell the End User what is the Error.....
    when i convert this exception as String by Using the following Code -
    Client.Java
    try {
    ///I am calling the CMP Bean here via Session Facade
    } catch (RemoteException e) {
    String actualExc = null;
    StringWritter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw); //This call prints the exception in console
    actualExc = sw.toString();///This string returns only the Stack levels classes ..Not the Exception.(I NEED THE FULL EXCEPTION DETAILS TO THIS STRING )
    How to convert this printStackTrace() exception into String ......Please if u need any other details i will give u..Any idea about this..
    Please reply me....

    Thanks for the reply. Is there any other way to get the actual exception thrown from the database level in CMP bean. Because i am getting only the RemoteException in Client. I am Using Whepshere/DB2.

  • How to catch SQLException from a session bean

    Hello
    I have a stateless session bean which has a method to persist an entity (User) in the database. In User there is a foreign key (addressId) from another entity (Address). While i was persisting User, i entered a value of addressId which was not present in the Address table. Since there was a foreign key constraint on this field in User i got the following exception:
    8:49:49,421 ERROR [JDBCExceptionReporter] ORA-02291:
    integrity constraint (FK_USER_ADD) violated - parent key not
    found 18:49:49,421 ERROR [AbstractFlushingEventListener]
    Could not synchronize database state with session
    org.hibernate.exception.ConstraintViolationException: could
    not insert: [com.User] at org.hibernate.exception.SQLStateConverter.convert(SQLState
    Converter.java:71)So i placed the persist code inside a try block and was catching all the exceptions thrown by persist() method. But these exception are not caught. Instead the exception is sent to the Client end and printed on the client console.
    Any clue on how to catch the ConstraintViolationException in the session bean?
    Thanks

    The problem is that the qry is not executed until you leave your method, so, the exception is catched by the Container. You should issue a entityManager.flush(); rigth "before" leaving the method and you are going to catch all the exceptions given
    Cheers

  • How to catch SQLException  in the hibernate ?

    Hi ~ , I am a newbie to java , recently I do a project that need to use hibernate to do insert data into database(db2) , but my program always encounter a DB deadlock problem , which throw an exception indicated that
    "{code}DB2 SQL error: SQLCODE: -911, SQLSTATE: 40001, SQLERRMC: 2{code}"
    so, in this case , i want to try catch block handle this exception , and the code is as follows:
    public static void main(String[] args){
    try {
    Configuration cfg =
    new Configuration().configure();
    SessionFactory sf = cfg.buildSessionFactory();
    Session session = sf.openSession();
    Transaction tx = session.beginTransaction();
    try {
    session.save(obj1);
    session.save(obj2);
    tx.commit();
    session.close();
    }catch (SQLException se) {
    // ***** here it indicate an error that "This exception is never thrown from the try statement body" *****
    }catch (HibernateException e) {
    e.printStackTrace();
    }but in fact , while running the programe , it does throw a SQLException that abend the program , how would I not be able to catch it ? , here I provide the error info :
    Hibernate: insert into TBCUSRPQ (CUST_NAME, CUST_SALUT, LAST_UPDT_BY, LANG, VER, FNL_RSK_LVL_CDE, SYS_RSK_LVL_CDE, CUS_RSK_LVL_CDE, NO_OF_ANS, ANS_REF_ID, DTL_INFO, BANK_NO, CTRY_CDE, RPQ_GP, CUST_ID_TYPE, CUST_ID_NO, LAST_UPDT_DT, LAST_UPDT_TM) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    Hibernate: insert into TBCUSANS (ANS_LIST, ANS_REF_ID, QUEST_NUM) values (?, ?, ?)
    Nov 5, 2008 12:04:17 PM net.sf.hibernate.util.JDBCExceptionReporter logExceptions
    WARNING: SQL Error: -911, SQLState: 40001
    Nov 5, 2008 12:04:17 PM net.sf.hibernate.util.JDBCExceptionReporter logExceptions
    SEVERE: DB2 SQL error: SQLCODE: -911, SQLSTATE: 40001, SQLERRMC: 2
    Nov 5, 2008 12:04:17 PM net.sf.hibernate.impl.SessionImpl execute
    SEVERE: Could not synchronize database state with session
    net.sf.hibernate.exception.GenericJDBCException: could not insert: [com.hsbc.rpq.importer.vo.ris.CustomerAnswer#com.hsbc.rpq.importer.vo.ris.CustomerAnswer@87235980]
    at net.sf.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:80)
    at net.sf.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:69)
    at net.sf.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
    at net.sf.hibernate.persister.AbstractEntityPersister.convert(AbstractEntityPersister.java:1331)
    at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:472)
    at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:436)
    at net.sf.hibernate.impl.ScheduledInsertion.execute(ScheduledInsertion.java:37)
    at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2449)
    at net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2435)
    at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2392)
    at net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2261)
    at net.sf.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:61)
    at com.hsbc.rpq.importer.TestDB.main(TestDB.java:78)
    {color:#ff0000}Caused by: com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -911, SQLSTATE: 40001, SQLERRMC: 2{color}
    at com.ibm.db2.jcc.c.fg.e(fg.java:1596)
    at com.ibm.db2.jcc.b.gb.o(gb.java:727)
    at com.ibm.db2.jcc.b.gb.g(gb.java:143)
    at com.ibm.db2.jcc.b.gb.a(gb.java:39)
    at com.ibm.db2.jcc.b.w.a(w.java:34)
    at com.ibm.db2.jcc.b.vb.g(vb.java:139)
    at com.ibm.db2.jcc.c.fg.n(fg.java:1177)
    at com.ibm.db2.jcc.c.gg.eb(gg.java:1862)
    at com.ibm.db2.jcc.c.gg.d(gg.java:2295)
    at com.ibm.db2.jcc.c.gg.W(gg.java:457)
    at com.ibm.db2.jcc.c.gg.executeUpdate(gg.java:440)
    at net.sf.hibernate.impl.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:22)
    at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:462)
    ... 8 moreI tried a lot , but couldn't solve the problem, could anyone help me , how to catch a SQLExcepion in this case , thanks in advance !!

    Hi,
    as corlettk said, you may only catch exceptions that are thrown at you directly (at least for checked exceptions...). If you really want to handle this specific error situation in any reasonable way, there is the possibility to catch what is thrown at you and inspect the cause of the exception provided.
    try {
        // some hibernate calls
    } catch (GenericJdbcException ge) {
        if(ge.getCause() != null && ge.getCause() instanceof SQLException) {
            SQLException se = (SQLException)ge.getCause();
            if(se.getErrorCode() == -911) {
                // your error handling for this case
            }else{
                throw ge; // do not swallow unhandled exceptions
        }else{
            throw ge // do not swallow unhandled exceptions
    }But such things quickly get quite ugly, e.g. if the SQLException is not the direct cause of the GenericJdbcException...so you should be aware what you are doing.
    Bye.

  • Catching SQLException in CMP Entity Bean

    I wana catch an SQLException which is raised while updating a record in DB through a CMP Entity bean method (violating a Foriegn key constraint). It throws to the client a RemoteException which contains a RollbackException which further contains an EJBException and finally it contains the required SQLException. The containment of exceptions is like RemoteException contains RollbackException contains EJBException contains SQLException.
    I know I can parse out the SQLException, but what if I wana know that which foriegn key constraint raised this excepton while updation.
    I'm naive in EJB's and I hope the forum will not turn down my trivial question.
    Regards
    Rana

    For example I have a table "Emplyee" having a field key "DeptID", "DeptID" is a foriegn key from table Department.
    I have a user interface which can update "Employee" table and another user interface for updating "Departments" table. I can try to update employee A's "DeptID" to 3 whereas somebody else has deleted "DeptID" 3 from the "Department" table, this results in a foriegn key constraint violation at DB level. Now I wana catch this exception and report it to the client that the updation was not successful. How I can catch this exception.
    The current situation is that the container throws a RemoteException. This RemoteException contains the following nested hierarchy of exceptions
    RollbackException>> EJBException>> SQLException.
    At client side I'm not sure which exception caused the RemoteException until and unless I can find the Deepest exception (SQLException in this case) in the nested hierarchy.
    How I can write the code for handling exception as RemoteException from the container can be in the result of many other Exceptions as well.
    Regards
    Rana

  • Do i need to set Resource Ref's in teh deploy tool for a CMP bean?

    Hi,
    I have a CMP bean which i have deployed, it doesnt work, in the server log shows the following.
    [#|2005-03-10T14:13:21.046+1030|WARNING|sun-appserver-pe8.1|javax.enterprise.system.container.ejb.entity.finder|_ThreadID=16;|JDO74004: Bean 'PersonEntityBean' method ejbFindByPrimaryKey:
    com.sun.jdo.api.persistence.support.JDODataStoreException: JDO76400: Got a JDBC SQLException while executing the SQL statement:
    SQL statement<select t0.person_id, t0.name from person t0 where t0.person_id = ?> with input values:java.lang.Integer:1.
    Please examine the SQLException for more information.
    NestedException: java.sql.SQLException: No database selected
    THe database has been set up in the connection pools, i thought this was enough, as there is no coded names in the implementation code, am i wrong?
    how do i get my CMP bean to communicate with the database?
    do i need to set up any references?
    thank you for your time
    Gavin.

    You set the JNDI name of the JDBC resource in deploytool. To do this, select your EJB JAR, select the General pane, and click Sun-specific Settings. Enter the JNDI name of your JDBC resource, and then set up the mappings & relationships. The J2EE 1.4 Tutorial's Container Managed Persistence Examples chapter has several examples that show how to do this.
    -Ian Evans

  • How to catch  Timestamp in bean

    hi
    in servlet I can use
    HttpSession userSession = req.getSession(true);
    HttpSession session=req.getSession();
    Timestamp accessed = new
    Timestamp(session.getLastAccessedTime());
    how can I got then in bean
    Thank you

    hi , thank you for the kindness reply,
    I guess is something else wrong so I post my codepublic boolean validate() {
             boolean allOk=true; 
             if (stuNumber.equals("")|| stuNumber.length() !=10) {
                 errors.put("stuNumber","Please enter a valid student Number");
                 stuNumber="";
                 allOk=false;
               } else {
                   try {
                       int x = Integer.parseInt(stuNumber);
                     } catch (NumberFormatException e) {
                       errors.put("stuNumber","Please enter a valid student Number");
                       stuNumber="";
                       allOk=false;
               }//else
             //add into database
             try {
                  //use getInstance() method to get object of java Calendar class
                   //Calendar cal = Calendar.getInstance();             
                   Timestamp myTimestamp = new Timestamp(new Calendar().getTimeInMillis());
                    db =connectionPool.getConnection();
                     Statement s = db.createStatement(); 
                     rs = s.executeQuery("SELECT*  FROM survey where stuNumber='"+stuNumber+"'");           
                 connectionPool.returnConnection(db);
                 int count =0;//how many rows we can find.
                while (rs.next()){
                    count++;
                connectionPool.returnConnection(db);
                if(count<1){                       
                    db.setAutoCommit(false);
                  String  sql="insert into survey(name, stuNumber, gender,facultyName,degree, year, quesOne, quesTwo, quesThree, quesFour, quesFive, quesSix,quesSeven, quesEight, quesNine,quesTen,quesEleven, quesTwelve, quesThirteen, quesFourteen,quesFifteen, quesSixteen, quesSeventeen, quesEighteen, quesNineteen, quesTwenty, quesTwentyOne,userIp,accessTime)";
                                       sql+="value(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        ps = db.prepareStatement(sql);
                         ps.setString(1, name);
                          ps.setString(2, stuNumber);
                          ps.setString(3, gender);
                          ps.setString(4, facultyName);
                          ps.setString(5, degree);
                          ps.setString(6, year);
                          ps.setString(7, quesOne);
                          ps.setString(8, quesTwo);
                          ps.setString(9, quesThree);
                          ps.setString(10, quesFour);
                          ps.setString(11, quesFive);
                          ps.setString(12, quesSix);
                          ps.setString(13, quesSeven);
                          ps.setString(14, quesEight);
                          ps.setString(15, quesNine);
                          ps.setString(16, quesTen);
                          ps.setString(17, quesEleven);
                          ps.setString(18, quesTwelve);
                          ps.setString(19, quesThirteen);
                          ps.setString(20, quesFourteen);
                          ps.setString(21, quesFifteen);
                          ps.setString(22, quesSixteen);
                          ps.setString(23, quesSeventeen);
                          ps.setString(24, quesEighteen);
                          ps.setString(25, quesNineteen);
                          ps.setString(26, quesTwenty);
                          ps.setString(27, quesTwentyOne);
                          ps.setString(28,userIp);
                          ps.setTimestamp(29,timeStampDat);
                          ps.executeUpdate();                   
                   db.commit();
                db.setAutoCommit(true);   
                connectionPool.returnConnection(db);
               }//end try
               catch (Exception e) {
                 System.out.println("Error populating myBean: " + e.toString());
             return allOk;        
    }

  • How to implement sql query in cmp bean?

    let's say that i want to join two tables and use grouping, counting and sorting expresion. it is no problem with sql query but what about cmp bean?
    of course i can make one bmp bean or session bean and run directly sql expresion, but then what is the point of using cmp beans?
    thanks
    winnicki

    If yout need post-query for filling descriptive colums (eg. department name in emploees) you should build a view object which includes the descriptive colums by joining the relevent tables

  • How to catch a SQLException like this

    HI,guys
    I'm now connection a mysql database with jdbc.for I had set a column unique,if I insert the column with same word twice,it will throw a SQLException.the Exception Message is below:
    ----------------------------------------------------------------------------------------------------------------------------------------java.sql.SQLException: Invalid argument value, message from server: "Duplicate entry 'cat1' for key 2"
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1651)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:889)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:956)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:1874)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1700)
         at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1569)
         at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:233)
         at com.genech.admin.utils.AddCategory.addcategory(AddCategory.java:52)
         at com.genech.admin.actions.AddCategoryAction.doBusiness(AddCategoryAction.java:47)
         at com.genech.admin.actions.AbstractAction.execute(AbstractAction.java:51)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:284)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:204)
         at filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:169)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:233)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:204)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:245)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:199)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:195)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:164)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:149)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:156)
         at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:972)
         at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:206)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:828)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:700)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:584)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
         at java.lang.Thread.run(Unknown Source)
    now I want to catch it.but I cannot make sure if I can ONLY catch this Exception but not others.who can help me?Thanks.

    try {
         con = DriverManager.getConnection("jdbc:mysql://computerName/databaseName",userName,password);
         stmt = con.createStatement();
         return true;
         catch(SQLException ex) {
         if(ex.getMessage().toUpperCase().compareTo("SERVER CONFIGURATION DENIES ACCESS TO DATA SOURCE")==0)
              createErrorWindow("Somebody is already logged in, please try again later");
         else
              createErrorWindow("Error establishing connection to remote machine!");
         return false;
    I do this do decide between different types of SQLExceptions - use exception.getMessage() and compare the string returned.
    Steve.

  • Error in deploying a cmp bean in j2ee 1.3

    Hi,
    I am deploying a cmr application using 3 cmp entity beans. while deloyment i get a error for one of the entity bean, studentEJB. the error is :
    For [ StudentEJB ]
    Error: There are no method permissions within this bean [ StudentEJB ]. Transaction attributes must be specified for the methods defined in the remote interface [ LocalStudent ]. Method [ getLastName ] has no transaction attribute defined.
    my LocalStudent file is:
    import javax.ejb.*;
    import java.util.*;
    public interface LocalStudent extends EJBLocalObject
    public String getStudentID();
    public String getFirstName();
    public String getLastName();
    public ArrayList getAddressList();
    public ArrayList getRosterList();
    public void addAddress(LocalAddress address);
    public void addRoster(LocalRoster roster);
    while no errors are coming for the studentID and firstName fields why is the error coming for lastName field ?
    three fields, studentID, firstName and lastName contain similar implementations in the LocalStudent and studentEJB class.
    wiating for an early response...
    Tanmoy

    Hello there!
    I am having a similar problem here also. I am trying to build a lab for test the J2EE tecnology in order for the company I work for switch our Cash Dispenser system to java.
    I have made a very simple entity EJB witch local interface is:
    public interface LabLocal extends EJBLocalObject
    String getExperiment();
    String getDescription();
    void setDescription(String description);
    String getResult();
    void setResult(String result);
    Local home is:
    public interface LabLocalHome extends EJBLocalHome
         LabLocal create( String experiment, String description, String result ) throws CreateException;
         LabLocal findByPrimaryKey( LabPK key ) throws FinderException;
         void remove();
    and the bean itself is:
    public class LabBean implements EntityBean
    private EntityContext ctx;
    private DataSource dataSource;
    public String experiment;
    public String description;
    public String result;
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#ejbActivate()
    public void ejbActivate() throws EJBException, RemoteException
    // nothing to do here people.
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#ejbLoad()
    public void ejbLoad() throws EJBException, RemoteException
    LabPK key = (LabPK)ctx.getPrimaryKey();
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try
    con = dataSource.getConnection();
    stmt = con.prepareStatement("SELECT description, result FROM laboratory WHERE experiment = ?");
    stmt.setString(1, key.experiment);
    rs = stmt.executeQuery();
    if( ! rs.next() )
    error( "no data found in ejbLoad for " + key, null);
    this.experiment = key.experiment;
    catch( SQLException se)
    error("Error in ejbLoad" + key, se);
    finally
    closeConnection(con, stmt, rs);
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#ejbPassivate()
    public void ejbPassivate() throws EJBException, RemoteException
    this.description = null;
    this.result = null;
    this.experiment = null;
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#ejbRemove()
    public void ejbRemove() throws RemoveException, EJBException, RemoteException
         LabPK key = (LabPK) ctx.getPrimaryKey();
         Connection con = null;
         PreparedStatement stmt = null;
         try
              con = dataSource.getConnection();
              stmt = con.prepareStatement("DELETE FROM laboratory WHERE experiment = ? ");
              stmt.setString(1, key.toString() );
              stmt.executeUpdate();
         catch( SQLException se )
              error( "Error deleting " + key, se );
         finally
              closeConnection(con, stmt, null);
         this.experiment = null;
         this.description = null;
         this.result = null;
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#ejbStore()
    public void ejbStore() throws EJBException, RemoteException
    Connection con = null;
    PreparedStatement stmt = null;
    try
    con = dataSource.getConnection();
    stmt = con.prepareStatement("UPDATE Laboratory SET description = ? , result = ? WHERE experiment = ? ");
    stmt.setString(1, this.description);
    stmt.setString(2, this.result);
    stmt.setString(3, this.experiment);
    stmt.executeUpdate();
    catch( SQLException se)
    error( "Error processing UPDATE statement.", se);
    finally
    closeConnection(con, stmt, null);
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#unsetEntityContext()
    public void unsetEntityContext() throws EJBException, RemoteException
    this.ctx = null;
    this.dataSource = null;
    /* (non-Javadoc)
    * @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
    public void setEntityContext(EntityContext arg0) throws EJBException, RemoteException
    this.ctx = arg0;
    InitialContext ic = null;
    try
    ic = new InitialContext();
    dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/teste");
    catch( NamingException ne)
    error( "error looking up depend EJB or resource. ", ne);
    public void error( String message, Exception e)
    throw new EJBException( message, e);
    public void closeConnection( Connection con, PreparedStatement stmt, ResultSet rs )
    try
         if( stmt != null )
         stmt.close();
    catch( SQLException se)
    System.out.println( "Data base error: " + se.toString() );
    try
         if( con != null)
         con.close();
    catch( SQLException se)
    System.out.println( "Data base error: " + se.toString() );
    public LabPK ejbCreate( String experiment, String description, String result ) throws CreateException
    LabPK key = new LabPK( experiment );
    try
    ejbFindByPrimaryKey( key );
    throw new CreateException( "Duplicate lab: " + key);
    catch( FinderException fe ){}
    Connection con = null;
    PreparedStatement stmt = null;
    try
    con = dataSource.getConnection();
    stmt = con.prepareStatement("INSERT INTO laboratory ( experiment, description, result ) VALUES (?, ?, ?) ");
    stmt.setString(1, experiment);
    stmt.setString(2, description);
    stmt.setString(3, result);
    catch( SQLException se )
    error( "Error creating lab: " + key, se);
    finally
    closeConnection(con, stmt, null);
    this.experiment = experiment;
    this.description = description;
    this.result = result;
    return key;
    public void ejbPostCreate(String experiment, String description, String result){}
    public LabPK ejbFindByPrimaryKey( LabPK key ) throws FinderException
         Connection con = null;
         PreparedStatement stmt = null;
         ResultSet rs = null;
         try
              con = dataSource.getConnection();
              stmt = con.prepareStatement("SELECT experiment FROM laboratory WHERE experiment = ?");
              stmt.setString(1, key.experiment );
              rs = stmt.executeQuery();
              if( !rs.next() )
                   throw new FinderException( "Unknown key: " + key );
              return key;
         catch( SQLException se )
              error( "Error in finding primary key for " + key, se );
         finally
         closeConnection(con, stmt, rs);
         return null;
    public String getExperiment()
    return this.experiment;
    public String getDescription()
    return this.description;
    public void setDescription(String description)
    this.description = description;
    public String getResult()
    return this.result;
    public void setResult(String result)
    this.result = result;
    I will omit the PK code in order to not create a longer than necessary post.
    I am using the deploytool�s Graphical interface to generate a standalone jar file. When I run the verify tool I get the following errors:
    For [ D:-Linux-Java-LabJar.jar#LabJar.jar#LabBean ]
    Error: There are no method permissions within this bean [ LabBean ]. Transaction attributes must be specified for the methods defined in the remote interface [ simpleEJB.LabLocal ]. Method [ getDescription ] has no transaction attribute defined.
    For [ D:-Linux-Java-LabJar.jar#LabJar.jar#LabBean ]
    Error: There are no method permissions within this bean [ LabBean ]. Transaction attributes must be specified for the methods defined in the remote interface [ simpleEJB.LabLocal ]. Method [ setDescription ] has no transaction attribute defined.
    For [ D:-Linux-Java-LabJar.jar#LabJar.jar#LabBean ]
    Error: There are no method permissions within this bean [ LabBean ]. Transaction attributes must be specified for the methods defined in the remote interface [ simpleEJB.LabLocal ]. Method [ getResult ] has no transaction attribute defined.
    For [ D:-Linux-Java-LabJar.jar#LabJar.jar#LabBean ]
    Error: There are no method permissions within this bean [ LabBean ]. Transaction attributes must be specified for the methods defined in the remote interface [ simpleEJB.LabLocal ]. Method [ getExperiment ] has no transaction attribute defined.
    For [ D:-Linux-Java-LabJar.jar#LabJar.jar#LabBean ]
    Error: There are no method permissions within this bean [ LabBean ]. Transaction attributes must be specified for the methods defined in the remote interface [ simpleEJB.LabLocal ]. Method [ setResult ] has no transaction attribute defined.
    I�ve read the forum in search for an good answer and found some sugestions to look in the security and transaction tab in order to force the tool to generate the entries for the methods. It did not helped at all.
    I tried to change the defaults in transaction tab from "required" to "mandatory". When I save, the tool presents the root screen of the jar file, but when I go check the values of the transaction atributes, they are again set to "required" .
    In the descriptor viewer for the application descriptor it shows:
    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Sun ONE Application Server 8.0 EJB 2.1//EN" "http://www.sun.com/software/sunone/appserver/dtds/sun-ejb-jar_2_1-0.dtd"> <sun-ejb-jar> <enterprise-beans> <name>LabJar</name> <unique-id>366779567</unique-id> <ejb> <ejb-name>LabBean</ejb-name> <jndi-name>LabBean</jndi-name> </ejb> </enterprise-beans> </sun-ejb-jar>
    I cant get to edit it when I try.
    I am using the "Deployment Tool for Java 2 Plataform Enterprise Edition 1.4" from the J2EE SDK 1.4_2 running on Windows 2000 SP4.
    Tks in advance,
    Leonardo.
    P.S.: Ok. Isnt it silly. I wrote all that, and then choose "supported" instead of mandatory, saved and verified that it saved the setting indeed. returned to required and runned the test. It worked.

  • How to catch exception in JSP????

    how to catch exception in JSP?
    I use JDeveloper 3.1
    I use connection with database .
    When I insert record in database
    when have duplicate of primary key
    how to catch this exception and
    back to previous page?
    I trying with folowing:
    <jsp:useBean id="RowEditor" class="oracle.jbo.html.databeans.EditCurrentRecord" scope="request">
    <% try {
    RowEditor.setUseJS(true);
    RowEditor.initialize(pageContext, "package2_Package2Module.Drzavi1View");
    RowEditor.setSubmitText("Save");
    RowEditor.setTargetUrl("Drzavi1View_SubmitInsertForm.jsp");
    RowEditor.createNewRow();
    RowEditor.setReleaseApplicationResources(true);
    RowEditor.render();
    catch(Exception e) {
    %>
    <script>
    alert("primary key duplication");
    history.back();
    </script>
    <% } %>
    but i't not working
    please help me

    i catch exceptions as you do, i don't have any problem...
    are you throwing the exception from your bean?
    actually i don't catch an Exception, but an SQLException...
    but it works... here is my code...
         try
    myclass.addElement(); // this is an insert into Oracle
    catch( DataBaseFailException e ) /// an exception that i throws inside after i receive an SQLException
              session.setAttribute("gMessage","e.getMessage()); // error code

  • How to catch up Exception message?

    i have a question while using try{ ... }catch{ ... } clauses. for when update, delete, databse, there might be error occurred. all to often i do not deal with the message, only if to check log when serious problem i have to find it out; but i hope to learn how if i am able to display message of my own while erro occurrs. for instance, when falling into SQLException, originaly i might just utilize
    }catch(SQLException e){
    e.printStackTrace();
    is it possible for me to catch up message inside the printStackTrace that may happen while errors appearing? (or only down to catch{} clause be the last deadline that i am able to use? because i hope i am able to capture error code like ora-1234 and tranlate it into messages that user, who doesn't know too much about pc, can understand easily while reporting bug; and not just saying "we have problem here!")
    that is, if 'A' situation popping out, i hope to direct it to error page with special message shown. so does the same error page with different message specified while 'B' situation found out!
    any suggestions would be appreciated~
    thanks in advice,

    printStackTrace isn't obligatory. It's basically what you do with an exception when you don't have anything more specific to do with it.
    You can certainly catch a specific exception at any level, including inside another try {} block.
    Even having caught an exception you can decide that you don't want to handle it at this point in the code, and throw it again.
    You might do:
    try {
         try {
           ... statment which migh cause a particular database exception
            } catch(SQLException e) {
            if(e.getMessage().startsWith("ORA-1232")) {
              .. do somthing usefull
             } else
            throw e;   // the particular SQL exception was unexpected so go on and crash
       catch(Exception e) {
         e.printStackTrace();   // unexpected program failure

  • Physical table name - abstract table name mapping in CMP Bean

    Hello,
    I am using a EJB 2.x bean deployed on a SJSAS 9 server. EJB has problem associating the EJB to the actual table
    Details are as follows:
    EJB name: AccountCMP
    Actual tablename : account
    Error
    ejb store called
    IM: postInvokeentity3.AccountBean145996470_ConcreteImpl@d6be89
    EJB5071: Some remote or transactional roll back exception occurred
    com.sun.jdo.api.persistence.support.JDODataStoreException: JDO76400: Got a JDBC SQLException while executing the SQL statement:
    insert into "ACCOUNTCMP"("DESCRIPTION", "ACCOUNTNAME", "BALANCE", "ACCID") values ( ?, ?, ?, ?).
    Please examine the SQLException for more information.
    NestedException: java.sql.SQLException: ORA-00942: table or view does not exist
    FailedObjectArray: [entity3.AccountBean145996470_JDOState@5332ca]
    Please note that the insert statement has the ejb-name (I think so, as my CMP EJB is called ACCOUNTCMP) instead of the actual tablename (account).
    I do have the account.dbschema file and sun-cmp-mappings.xml in the NB 5.5 project, but the mappings.xml file is not included in the jar by NB. Is that expected, or an problem.
    sun-cmp-mappings.xml
    <sun-cmp-mappings>
      <sun-cmp-mapping>
        <schema>account</schema>   
        <entity-mapping>
          <ejb-name>AccountCMP</ejb-name>
          <table-name>account</table-name>
          <cmp-field-mapping>
    ejb-jar.xml
    <enterprise-beans>
            <entity>
                <ejb-name>AccountCMP</ejb-name>
                <local-home>entity3.AccountLocalHome</local-home>
                <local>entity3.AccountLocal</local>
                <ejb-class>entity3.AccountBean</ejb-class>           
                <persistence-type>Container</persistence-type>
                <prim-key-class>entity3.AccountPK</prim-key-class>
                <reentrant>false</reentrant>
                <cmp-version>2.x</cmp-version>           
                <abstract-schema-name>account</abstract-schema-name>  Thank you for your help.

    Hello,
    I found out the issue. sun-cmp-mappings.xml file is mandatory, and dont know why, netbeans excludes this file from the jar. I had to edit project.properties file to negate this exclusion.
    Another problem was that my table did not have a primary key (and hence by schema file did not have it also). CMP bean code generator did not like this.
    Once I fixed these two problems, my CMP started working fine.
    Thank you all

  • How to catch exception when have max connection pool

    hi,
    i have define in oracle user that i could have max 10 sessions at the same time.
    I have jdbc datasource & connection pool defined at glassfish server(JSF application).
    now, if in application is too many queries to the database then i have error: nullpointer exception - becouse when i try to do:
    con = Database.createConnection(); - it generates nullpointer exception becouse there isn't free connection pool
    i try to catch exception like this:
    public List getrep_dws_wnioski_wstrzymane_graph() {     int i = 0;     try {     con = Database.createConnection();     ps =    (Statement) con.createStatement();     rs = ps.executeQuery("select data, klasa, ile_dni_wstrzymana, ile_wnioskow from stg1230.dwsww_wstrzymane_dws8 order by data, klasa, ile_dni_wstrzymana, ile_wnioskow");     while(rs.next()){       rep_dws_wnioski_wstrzymane_graph.add(i,new get_rep_dws_wnioski_wstrzymane_graph(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)));       i++;     }     } catch (NamingException e) {         e.printStackTrace();     } catch (SQLException e) {         e.printStackTrace();     } catch (NullPointerException e) {         e.printStackTrace();         throw new NoConnectionException();  // catch null 1     } finally {     try {         con.close();     } catch (SQLException e) {         e.printStackTrace();     } catch (NullPointerException e) {         e.printStackTrace();         throw new NoConnectionException();  // catch null 2     }     } return rep_dws_wnioski_wstrzymane_graph; }
    but at line:
    con.close();
    i have nullpointerexception
    and
    at line
    throw new NoConnectionException(); // catch null 2
    i have: caused by exception.NoConnectionException
    what's wrong with my exception class? how to resolve it?
    public class NoConnectionException extends RuntimeException{     public NoConnectionException(String msg, Throwable cause){       super(msg, cause);     }     public NoConnectionException(){       super();     } }
    at web.xml i have defined:
    <error-page>         <exception-type>exception.NoConnectionException</exception-type>         <location>/NoConnectionExceptionPage.jsp</location>     </error-page>

    thanks,
    i did it and i have error:
    java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: ORA-02391: exceeded simultaneous SESSIONS_PER_USER limit
    at com.sun.gjc.spi.base.DataSource.getConnection(DataSource.java:115)
    at logic.Database.createConnection(Database.java:37): conn = ds.getConnection();
    public class Database {
         public static Connection createConnection() throws NamingException,
                    SQLException {
                Connection conn = null;
                try{
                    Context ctx = new InitialContext();
              if (ctx == null) {
                   throw new NamingException("No initial context");
              DataSource ds = (DataSource) ctx.lookup("jdbc/OracleReports");
              if (ds == null) {
                   throw new NamingException("No data source");
              conn = ds.getConnection();  // here's exception when max connections to database
              if (conn == null) {
                   throw new SQLException("No database connection");
                } catch (NamingException e) {
                    e.printStackTrace();
                    throw new NoConnectionException(); 
             } catch (SQLException e) {
                 e.printStackTrace();
                    throw new NoConnectionException(); 
                catch (NullPointerException e) {
                 e.printStackTrace();
                    throw new NoConnectionException();  // obsluga bledy na wypadek jesli braknie wolnych polaczen do bazy
            return conn;
    }and at my ealier code i have error:
    at logic.GetDataOracle.getrep_dws_wnioski_wstrzymane_graph(GetDataOracle.java:192)
    at line: con = Database.createConnection();
    in code:
    public List getrep_dws_wnioski_wstrzymane_graph() {
        int i = 0;
        try {
        con = Database.createConnection();
        ps =    (Statement) con.createStatement();
        rs = ps.executeQuery("select data, klasa, ile_dni_wstrzymana, ile_wnioskow from stg1230.dwsww_wstrzymane_dws8 order by data, klasa, ile_dni_wstrzymana, ile_wnioskow");
        while(rs.next()){
          rep_dws_wnioski_wstrzymane_graph.add(i,new get_rep_dws_wnioski_wstrzymane_graph(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)));
          i++;
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new NoConnectionException();
        } finally {
        try {
            if(con != null)
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw new NoConnectionException(); 
    return rep_dws_wnioski_wstrzymane_graph;
    }so what's wrong?
    i have limit max sessions 10 at oracle so i set at my connection pool 5 connections as max. But when i get max 5 sesssins and try to execute next query then i can't catch exception..

Maybe you are looking for