EntityManager in EJB3 CMT

Hi
I'm getting a List of Entitys by
String _selectStr = "SELECT a FROM " + GNebenengGruppenverwEntity.class.getSimpleName() + "  a";
Query query = getEntityManager().createQuery(_selectStr);
return (Collection<GNebenengGruppenverwEntityIF>) query.getResultList();I'm getting them for read only purposes. But by getting them in this way they are managed by the entity manager. Every time about 13'000 Entitys are created and managed. If a User opens and closes the screan 3 times in a row the EntityManager tries to get these 13'000 Entitys parallel.
Is there a possibility to stop the entityManager from getting the List or at least say him he should get the list but do not manage them (whould at least save some memory).

If I use EntityManager.createNativeQuery(String) then I get results which are of course not bound in the entityManager but I have problems to Map all the returned Types like BigDecimal to something useful like Long. If I whould use EntityManager.createNativeQuery(String sql, String resultSetName) then this whould be handled, but is the returned Entity then again handled by the EntityManager?
And 2nd what I'm doing wrong? On the Entity I declared:
@SqlResultSetMapping(name="getList", entities={
    @EntityResult(entityClass = GNebenengGruppenverwEntity.class, fields = {
      @FieldResult(name = "NEG_KEY", column = "key")
      @FieldResult(name = "NEG_BEZEICHNUNG", column = "bezeichnung")
    })})and in the Bean I use:
String _selectStr = "SELECT kn.NEG_KEY key, kn.NEG_BEZEICHNUNG bezeichnung FROM re_nebenengagement kn";
final Query query = getEntityManager().createNativeQuery(_selectStr, "getList");
List result = query.getResultList();I always get
java.sql.SQLException: Ung�ltiger Spaltenname
and on the Output from JBoss I have:
DEBUG 2007-10-25 11:18:41,083 [AbstractBatcher] about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
DEBUG 2007-10-25 11:18:41,083 [ConnectionManager] opening JDBC connection
DEBUG 2007-10-25 11:18:41,099 [SQL] SELECT kn.NEG_BEZEICHNUNG bezeichnung FROM kre_nebenengagement kn
DEBUG 2007-10-25 11:18:41,099 [AbstractBatcher] about to open ResultSet (open ResultSets: 0, globally: 0)
INFO 2007-10-25 11:18:41,099 *[LongType] could not read column value from result set: NEG1_39_0_; Ung�ltiger Spaltenname*DEBUG 2007-10-25 11:18:41,099 [AbstractBatcher] about to close ResultSet (open ResultSets: 1, globally: 1)
DEBUG 2007-10-25 11:18:41,099 [AbstractBatcher] about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
DEBUG 2007-10-25 11:18:41,099 [ConnectionManager] aggressively releasing JDBC connection
DEBUG 2007-10-25 11:18:41,115 [ConnectionManager] releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
DEBUG 2007-10-25 11:18:41,115 [JDBCExceptionReporter] could not execute query [SELECT kn.NEG_BEZEICHNUNG bezeichnung FROM kre_nebenengagement kn]

Similar Messages

  • EJB3 / TopLink EntityManager - invalid query key in expression

    with Glassfish and TopLinka s the entity manager, I'm getting an QueryException that I don't understand. The complaint is that my key (enamelId) is invalid. However I can use the same key in a different query successfully.
    Any thoughts?
    this query gets no complaints:
    SELECT sh FROM Showpiece as sh WHERE sh.enamelId = '0301'
    this query fails:
    SELECT ex FROM Exhibition as ex, Showpiece as sh WHERE sh.enamelId = '0301' AND ex.id = sh.showId
    Exception [TOPLINK-6015] (Oracle TopLink Essentials - 2006.4 (Build 060412)): oracle.toplink.essentials.exceptions.QueryException
    Exception Description: Invalid query key [enamelId] in expression.
    Query: ReportQuery(com.schwarcz.enamels.model.Exhibition)
    at oracle.toplink.essentials.exceptions.QueryException.invalidQueryKeyInExpression(QueryException.java:608)
    at oracle.toplink.essentials.internal.expressions.QueryKeyExpression.validateNode(QueryKeyExpression.java:657)
    at oracle.toplink.essentials.expressions.Expression.normalize(Expression.java:2542)
    at oracle.toplink.essentials.internal.expressions.DataExpression.normalize(DataExpression.java:343)

    I don't remember the specifics of my solution. The base cause was indeed an error in my code. I dimly remember that I had written something so that TopLink was trying to generate a join table and I had defined one as a POJO as well. What I do remember was what I did to find a solution...
    I switched to using the Hibernate entity manager, got some different error messages and was able to correct my code. I now routinely switch back and forth between TopLink and Hibernate. Both seem to me to be pretty likely to produce error messages that are vague and not too helpful.

  • EJB3: When do Entities get detached in practice?

    Hi,
    I am currently improving my first EJB3 / JSF prototype in order to get a good feeling for that new technology. I am using Sun Appserver 9, NetBeans 5.5.
    I have the followiong design-setup:
    JSF-BackingBean ===uses===> @Remote Stateless Session Bean ===fetches==> EntityBeans
    The general question is: 1.) Where do EntityBeans get detached in a JSF setup and 2.) does detaching mean, that I cannot traverse the relations anymore, even if I have eager fetching configured`?
    Let me also ask some more detailed questions:
    The Backing Bean stores the Entity Bean "A" in an attribute. So far so good. My Entity A has a 1:n association to Entity B with eager fetching configured in the annotation. When I now want to access the relation getBs() from within a JSF forEach statement, I keep getting an error from the persistence layer.
    I found out, that if my Stateless Session Bean accesses getBs() after having retrieved A before it returns, then it works also from the JSF page. From my current understanding, eager fetching should have had the same effect....???!!!
    Anyway, I read the EJB persistence specs and in chapter 5.6.3 it says, that:
    Propagation of persistence contexts only applies within a local
    environment. Persistence contexts are not propagated to remote tiers.Does this mean, that Entities get detached at this point? But why does it then work even remotely, when I access getBs() from the SLSB?
    Furthermore, if I used a Local Interface for the SLSB, can I then expect this to work without the call to getBs()?
    Would it have an impact to inject an EntityManager into the BackingBean? From my current understanding, container-managed transactions are demarcated through the SLSB, so the transaction would end there anyway, so I suppose injecting the EntityManager into the BackingBean does NOT have an impact. Can anybody confirm this?
    Many Thanks in advance,
    Stephan

    Hi,
    Hi Stephan. Great questions. Answers inline.
    I am currently improving my first EJB3 / JSF
    prototype in order to get a good feeling for that new
    technology. I am using Sun Appserver 9, NetBeans
    5.5.
    I have the followiong design-setup:
    JSF-BackingBean ===uses===> @Remote Stateless Session
    Bean ===fetches==> EntityBeans
    The general question is: 1.) Where do EntityBeans get
    detached in a JSF setup It's independent of JSF itself. The detaching behavior depends on what kind of interface (local vs. remote) is used to access the Stateless Session bean and what the transactional settings are for the invocation. First off, any Java Persitence API entities passed through a Remote interface become detached when received by the caller, even if the caller is in the same application as the callee.
    If the related entities were not fetched before the detachment, they will not be available after detachment.
    If you use a Local interface to access the Stateless Session Bean, detachment will occur when the transaction within which the entities were fetched commits or rolls back. My guess is you're using the default tx behavior (CMT/TX_REQUIRED) for the SLSB business method and not demarcating transactions in the JSF bean, so the entities will become attached when the SLSB method returns.
    and 2.) does detaching mean,
    that I cannot traverse the relations anymore, even if
    I have eager fetching configured`?You can try traversing afterwards but there's no guarantee the requested
    entities will be there. If they happened to have been fetched before
    the detachment, they will be returned. Otherwise, they won't be found and
    since the entities are no longer associated with an entity manager, it's too
    late for them to be fetched.
    >
    Let me also ask some more detailed questions:
    The Backing Bean stores the Entity Bean "A" in an
    attribute. So far so good. My Entity A has a 1:n
    association to Entity B with eager fetching
    configured in the annotation. When I now want to
    access the relation getBs() from within a JSF forEach
    statement, I keep getting an error from the
    persistence layer.
    I found out, that if my Stateless Session Bean
    accesses getBs() after having retrieved A before it
    returns, then it works also from the JSF page. From
    my current understanding, eager fetching should have
    had the same effect....???!!!That only applies to a managed entity. When it's in the
    detached state, the eager fetching doesn't apply since
    it's not associated with an EntityManager.
    Anyway, I read the EJB persistence specs and in
    chapter 5.6.3 it says, that:
    Propagation of persistence contexts only applieswithin a local
    environment. Persistence contexts are not propagatedto remote tiers.Persistence context propagation refers to the case where
    two different Java EE components within the same transaction both access a
    container-managed transactional EntityManager. If both components are within
    the same application and running on the same JVM, they will "see" the same
    persistence context. This is magic performed by the container to preserve
    the transactional semantics from the Entity Bean model in J2EE 1.4 and earlier.
    E.g, if your JSF bean had a container-managed entity manager and started
    a global transaction, then invoked a Stateless Session Bean method with
    TX_REQUIRED, the JSF bean's EntityManager would have the same
    state as the Stateless Session Bean's EntityManager, without having to explicitly
    pass references to entity classes between them.
    >
    Furthermore, if I used a Local Interface for the
    SLSB, can I then expect this to work without the call
    to getBs()? Only if you start a global transaction before invoking the SLSB and call
    getBs() before committing the tx.
    Would it have an impact to inject an EntityManager
    into the BackingBean? Yes, that's one way to do it, but you also need to ensure that the same tx is being used. See below.
    From my current understanding,
    container-managed transactions are demarcated through
    the SLSB, so the transaction would end there anyway,It depends on which transaction attribute is used. For the default tx attribute (TX_REQUIRED), if there is an existing transaction when the SLSB is accessed that will be used instead of the container starting a new one, which means it will not be committed by the container when the SLSB method returns.
    so I suppose injecting the EntityManager into the
    BackingBean does NOT have an impact. Can anybody
    confirm this?Not true. See above. There's a good JavaOne talk on the topic of web-tier use of the Java Persistence API given by Linda Demichiel, Gavin King, and Craig McClanahan.
    You can find it here :
    http://developers.sun.com/learning/javaoneonline/2006/webtier/TS-1887.html
    --ken
    >
    Many Thanks in advance,
    Stephan

  • Com.sap.sql.log.OpenSQLException during EntityManager Call

    Hi!
    I deployed an EJB3 session bean on the NW 7.1.
    The aim is to use JPA with this bean.
    I configured the "persistence.XML" for the bean project and packed it into the jar File and a "data-source-aliases.xml" which is included in the ear file. The packaging of the ear-file is done with the developerStudio and deployed on the NW 7.1
    Then I created a dataSource project which contains the "data-sources.xml" and deployed this too.
    Here is my data-sources.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE data-sources SYSTEM 'data-sources.dtd'>
    <data-sources>
        <data-source>
            <data-source-name>JPA_SDN_EXAMPLE_DS_555</data-source-name>
            <driver-name>ora10</driver-name>
            <sql-engine>native_sql</sql-engine>
            <jdbc-1.x>
                <driver-class-name>oracle.jdbc.driver.OracleDriver</driver-class-name>
    <!-- *** Edit the following entries appropriately *** -->
                <url>jdbc:oracle:thin:@10.XXX.7.27:1521:orcl</url>
                <user-name>bdeadm</user-name>
                <password>dmin</password>
    <!-- *** End editing ***  -->
            </jdbc-1.x>
        </data-source>
    </data-sources>
    My deployed session bean looks like this:
    @Stateless(name="WorkerBean")
    public class WorkerBean implements WorkerRemote {
         @PersistenceContext(unitName="JPAModel")
        private EntityManager em;
         public String sayHello() {
    The last step was the deploment of the oracle driver on the NW7.1 under the "Application Resources Overview". The driver I named "ora10".
    Now if I call my Bean shown above with its Entity Manager Call for the injection I got the following exception:
    Caused by: com.sap.sql.log.OpenSQLException: Error while accessing porting layer for ORACLE database via getSessionId().
         at com.sap.sql.log.Syslog.createAndLogOpenSQLException(Syslog.java:148)
         at com.sap.sql.jdbc.direct.DirectConnectionFactory.createPooledConnection(DirectConnectionFactory.java:532)
         at com.sap.sql.jdbc.direct.DirectConnectionFactory.createDirectPooledConnection(DirectConnectionFactory.java:157)
         at com.sap.sql.jdbc.direct.DirectConnectionFactory.createDirectPooledConnection(DirectConnectionFactory.java:117)
         at com.sap.sql.connect.factory.PooledConnectionFactory.createPooledConnection(PooledConnectionFactory.java:119)
         at com.sap.sql.connect.factory.DriverPooledConnectionFactory.getPooledConnection(DriverPooledConnectionFactory.java:38)
    I have no idea, whats wrong. Perhaps my driver is wrong or not set properly ?
    Can anybody help me please ?
    Thanks in advance,
    Hendrik
    Edited by: henne123 on May 18, 2009 6:19 PM

    I have tried that.
    [EXCEPTION]
    *com.sap.sql.log.OpenSQLException: The SQL statement "SELECT * FROM EPD.SAPEPDDB.UME_EP_SLD" contains the syntax error[s]: - Open SQL syntax error: table names must not specify a catalog name (delete "EPD". before "SAPEPDDB"."UME_EP_SLD")*
    Database name must be Ok, because i can access to other tables which are in the same DB...
    Thanks for your help

  • Problem with rollback in EJB and CMT

    Hello,
    I faced a problem in my application that I really do not understand (but I really would like to). How can I trigger a rollback of a transaction that is container-managed (CMT)? I know that any system exceptions are supposed to be handled by the container automatically and will cause a transaction rollback when they are thrown from an enterprise bean method. My Problem now is that I'm unable to make this work in my application.
    Consider a situation like this:
    The ManageEntityBean holds a simple save() method that creates an instance of EntityA and another of EntityB. Both instances store an arbitrary number (here 10). After this, the entityManger (injected from the container) is asked to make these instances persistent. EntityB is mapped with a "unique" constraint, so any attempt to store the same number twice will cause an SQL Exception.
    First time when the save() method is invoked, the instances aEntity and bEntity are made permanent in the database. Second time when the save() method is invoked, the database throws an exception because bEntity is violating the unique constraint. What I would expect now is a complete rollback of the whole transaction. Instead, only bEntity has not been made permanent, but aEntity has.
    What's wrong with this code?
    @Stateless
    public class ManageEntityBean implements ManageEntity {
         @PersistenceContext
         private EntityManager entityManager;
         @TransactionAttribute(TransactionAttributeType.REQUIRED)
         public void save() {
              try {
                   EntityA aEntity = new EntityA(10);
                   EntityB bEntity = new EntityB(10);
                    entityManager.persist(aEntity);
                    entityManager.persist(bEntity);
              } catch (Exception e) {
                   throw new EJBException(e);
    @Entity
    public class EntityA implements java.io.Serializable {
         @Id
         @GeneratedValue
         private long     id;
            @Column(name="NUMBER")
            private int   number;
         public EntityA() {}
         public EntityA(int number) {
              this.number = number;
    @Entity
    public class EntityB implements java.io.Serializable {
         @Id
         @GeneratedValue
         private long     id;
         @Column(name = "NUMBER", unique = true)
         private int          number;
         public EntityB() {}
         public EntityB(int number) {
              this.number = number;
    }I found two related topics in this forum but still I didn't find the solution yet.
    [Enterprise JavaBeans - CMT and JDBC|http://forums.sun.com/thread.jspa?forumID=13&threadID=525651]
    and
    [ Forums - A CMT Session Bean Does Not Maintain the Transaction Correctly| http://forums.sun.com/thread.jspa?forumID=13&threadID=161512]
    Maybe anyone can give me a hint. Help is very much appreciated
    Christoph

    Thank you for your input!
    The save() method is simply invoked from the test applications main() method:
    public class Test {
         public static void main(String[] args) {
              JndiUtil<ManageEntity> jndiUtil = new JndiUtil<ManageEntity>();
              ManageEntity handler = jndiUtil.lookupBeanContext("ManageEntityBean", ManageEntity.class);
              handler.save();
    }Btw. I use Hibernate as persistence provider and JBoss 4.2.2.GA as application server.
    For clarity I attach some lines of the debug logging that is produced when the test application is getting started for the second time:
    ### open Session
    17:44:00,555 DEBUG *[SessionImpl] opened session at timestamp: 5007498610909184*
    17:44:00,555 DEBUG [AbstractEntityManagerImpl] Looking for a JTA transaction to join
    17:44:00,555 DEBUG [JDBCContext] successfully registered Synchronization
    17:44:00,555 DEBUG [AbstractEntityManagerImpl] Looking for a JTA transaction to join
    17:44:00,555 DEBUG [AbstractEntityManagerImpl] Transaction already joined
    ### invoke em.persist(aEntity)
    17:44:00,555 DEBUG [AbstractSaveEventListener] executing identity-insert immediately
    17:44:00,555 DEBUG [AbstractBatcher] about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
    17:44:00,555 DEBUG *[ConnectionManager] opening JDBC connection*
    17:44:00,555 DEBUG [SQL]
    /* insert de.zippus.domain.EntityA
    17:44:00,556 INFO [STDOUT] Hibernate:
    /* insert de.zippus.domain.EntityA
    17:44:00,558 DEBUG [IdentifierGeneratorFactory] Natively generated identity: 2
    17:44:00,559 DEBUG [AbstractBatcher] about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    17:44:00,559 DEBUG [ConnectionManager] aggressively releasing JDBC connection
    17:44:00,559 DEBUG [ConnectionManager] releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: >0)]
    ### invoke em.persist(bEntity)
    17:44:00,559 DEBUG [AbstractSaveEventListener] executing identity-insert immediately
    17:44:00,559 DEBUG [AbstractBatcher] about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
    17:44:00,559 DEBUG [ConnectionManager] opening JDBC connection
    17:44:00,559 DEBUG [SQL]
    /* insert de.zippus.domain.EntityB
    17:44:00,560 INFO [STDOUT] Hibernate:
    /* insert de.zippus.domain.EntityB
    17:44:00,561 DEBUG [AbstractBatcher] about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
    17:44:00,561 DEBUG [ConnectionManager] aggressively releasing JDBC connection
    17:44:00,561 DEBUG [ConnectionManager] releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: >0)]
    17:44:00,561 DEBUG [JDBCExceptionReporter] could not insert: [de.zippus.domain.EntityB] [* insert de.zippus.domain.EntityB */ insert into >ENTITY_B (NUMBER) values (?)]
    com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '10' for key 2
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
    17:44:00,563 WARN [JDBCExceptionReporter] SQL Error: 1062, SQLState: 23000
    17:44:00,563 ERROR [JDBCExceptionReporter] Duplicate entry '10' for key 2
    17:44:00,563 DEBUG [AbstractEntityManagerImpl] mark transaction for rollback
    17:44:00,563 ERROR [ManageEntityBean] Caught exception: javax.persistence.EntityExistsException: >org.hibernate.exception.ConstraintViolationException: could not insert: [de.zippus.domain.EntityB]
    17:44:00,563 ERROR [ManageEntityBean] Exception Cause: org.hibernate.exception.ConstraintViolationException: could not insert: >[de.zippus.domain.EntityB]
    17:44:00,564 DEBUG *[ManagedEntityManagerFactory] ************** closing entity managersession *************** Up to now I'm not that experienced in reading and understanding this kind of logging, but what I can see is, that there is a transaction that spans the whole unit of work and that this transaction is marked for rollback. I think that's quite a good thing, isn't it?
    But what really puzzles me here is, that both calls of em.persist() result in an opening of a jdbc connection and an immidiate execution of a database insert. Tell me if I'm wrong, but is this really the right place to happen?
    For what reason soever hibernate thinks it has to make these instances permanent, no matter if there is already a session that is taking care of this. If so, I might deal with a wrong hibernate configuration, I checked, but I can't find anything..
    What do you think?
    Thanks in advance!
    Christoph

  • EJB 3.0 (MDB) CMT does partial Tx commit in hibernate

    Seems like CMT (MDB) does partial commit.+
    A secnario like this: we are using EJB3.0 combination with Hibernate
    1. Some message sent to queue.
    2. MDB listner who listen the queue its onMessage method is invoked. See below for MDB configurations.
    @TransactionManagement(TransactionManagementType.CONTAINER)
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    3. Some Handler is called from MDB say ResponseHandler.
    4. We called 2 update operation from this handler.
    ResponseHandler#updateTable1() with below set of execution
    |__ em.merg(table1Entity);
    |__ em.flush()
    ResponseHandler#updateTable2() with below set of execution
    |__ em.merg(table2Entity);
    |__ em.flush()
    Problem:+
    I can see only one table1 is get updated. Table2 is not updated with latest value though MDB class is container managed...
    Hibernate query logs: In logs i can see update operation for both the tables
    Hibernate: update table1...
    Hibernate: update table2...
    PS: We can't see this problem in case we put debug breakpoint on first line of onMessage() method of MDB
    class ResponseListner implements MessageListener
    public void onMessage(final Message message)
    Logger.info("ResponseListner.onMessage() : Entered"); //breakpoint line (breakpoint is here)
    Weblogic transaction logs+
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <> <> <1333538349228> <BEA-000000> <BEA1-0012DE77F7FE1343F773: null: XA.prepare(rm=WLStore_application_cluster_domain2_applicationServerJDBCStore, xar=WLStore_application_cluster_domain2_applicationServerJDBCStore234212480>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <> <> <1333538349228> <BEA-000000> <startResourceUse, Number of active requests:1, last alive time:0 ms ago.>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349233> <BEA-000000> <BEA1-0012DE77F7FE1343F773: null: XA.prepare DONE:ok>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349233> <BEA-000000> <endResourceUse, Number of active requests:0>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAJDBC> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349233> <BEA-000000> <JDBC LLR pool='com.application.ds' xid='BEA1-0012DE77F7FE1343F773' tbl='WL_LLR_applicationSERVER': begin write XA record table=WL_LLR_applicationSERVER recLen=529>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAJDBC> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349234> <BEA-000000> <JDBC LLR pool='com.application.ds' xid='BEA1-0012DE77F7FE1343F773' tbl='WL_LLR_applicationSERVER': after write XA record>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAJDBC> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349234> <BEA-000000> <JDBC LLR pool='com.application.ds' xid='BEA1-0012DE77F7FE1343F773' tbl='WL_LLR_applicationSERVER': commit one-phase=false>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAJDBC> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349239> <BEA-000000> <JDBC LLR pool='com.application.ds' xid='BEA1-0012DE77F7FE1343F773' tbl='WL_LLR_applicationSERVER': commit complete>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <> <> <1333538349240> <BEA-000000> <startResourceUse, Number of active requests:1, last alive time:0 ms ago.>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349243> <BEA-000000> <BEA1-0012DE77F7FE1343F773: null: XA.commit DONE (rm=WLStore_application_cluster_domain2_applicationServerJDBCStore, xar=WLStore_application_cluster_domain2_applicationServerJDBCStore234212480>
    ####<Apr 4, 2012 4:49:09 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <api.user1> <BEA1-0012DE77F7FE1343F773> <> <1333538349243> <BEA-000000> <endResourceUse, Number of active requests:0>
    ####<Apr 4, 2012 4:49:10 PM IST> <Info> <Health> <inlinapplication001> <applicationServer> <weblogic.GCMonitor> <<anonymous>> <> <> <1333538350589> <BEA-310002> <39% of the total memory in the server is free>
    ####<Apr 4, 2012 4:49:26 PM IST> <Debug> <JTAXA> <inlinapplication001> <applicationServer> <[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <BEA1-0014DE77F7FE1343F773> <> <1333538366645> <BEA-000000> <ResourceDescriptor[WLStore_application_cluster_domain2__WLS_applicationServer]: getOrCreate gets rd: name = WLStore_application_cluster_domain2__WLS_applicationServer
    resourceType = 2
    registered = true
    scUrls = applicationServer+10.19.216.10:5003+application_cluster_domain2+t3+
    xar = WLStore_application_cluster_domain2__WLS_applicationServer1926833320
    healthy = true
    lastAliveTimeMillis = 1333538336966
    numActiveRequests = 0
    >

    You have to add the property toplink.ddl-generation.output-mode to your persistence.xml file, for example:
    <?xml version="1.0" encoding="windows-1252" ?>
    <persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="model">
    <jta-data-source>jdbc/jdm-akoDS</jta-data-source>
    <properties>
    <property name="toplink.logging.level" value="INFO"/>
    <property name="toplink.target-database" value="Oracle"/>
    <property name="toplink.ddl-generation" value="drop-and-create-tables"/>
    <property name="toplink.ddl-generation.output-mode" value="database"/>
    </properties>
    </persistence-unit>
    </persistence>

  • Ejb3 bean not bound

    Hi I am new to EJB . Now in our project we are using ejb3 and persistance. So tried
    a simple program which I found out from net. But when I am trying to run I am getting
    bean not bound. And in JBoss console it is showing error like
    ObjectName: jboss.jca:service=DataSourceBinding,name=DefaultDS State: NOTYETINSTALLED
    These are all my files.
    Book.java
    package de.laliluna.library;
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    @Entity
    @Table(name="book")
    @SequenceGenerator(name = "book_sequence", sequenceName = "book_id_seq")
    public class Book implements Serializable {
         private static final long serialVersionUID = 7422574264557894633L;
         private Integer id;
         private String title;
         private String author;
         public Book() {
              super();
         public Book(Integer id, String title, String author) {
              super();
              this.id = id;
              this.title = title;
              this.author = author;
         @Override
         public String toString() {
              return "Book: " + getId() + " Title " + getTitle() + " Author "
                        + getAuthor();
         public String getAuthor() {
              return author;
         public void setAuthor(String author) {
              this.author = author;
         @Id
         @GeneratedValue(strategy = GenerationType.TABLE, generator = "book_id")
         public Integer getId() {
              return id;
         public void setId(Integer id) {
              this.id = id;
         public String getTitle() {
              return title;
         public void setTitle(String title) {
              this.title = title;
    }BookTestBean.java
    package de.laliluna.library;
    import java.util.Iterator;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    @Stateless
    public class BookTestBean implements BookTestBeanLocal, BookTestBeanRemote {
         @PersistenceContext(name="FirstEjb3Tutorial")
         EntityManager em;
         public static final String RemoteJNDIName =  BookTestBean.class.getSimpleName() + "/remote";
         public static final String LocalJNDIName =  BookTestBean.class.getSimpleName() + "/local";
         public void test() {
              Book book = new Book(null, "My first bean book", "Sebastian");
              em.persist(book);
              Book book2 = new Book(null, "another book", "Paul");
              em.persist(book2);
              Book book3 = new Book(null, "EJB 3 developer guide, comes soon",
                        "Sebastian");
              em.persist(book3);
              System.out.println("list some books");
              List someBooks = em.createQuery("from Book b where b.author=:name")
                        .setParameter("name", "Sebastian").getResultList();
              for (Iterator iter = someBooks.iterator(); iter.hasNext();)
                   Book element = (Book) iter.next();
                   System.out.println(element);
              System.out.println("List all books");
              List allBooks = em.createQuery("from Book").getResultList();
              for (Iterator iter = allBooks.iterator(); iter.hasNext();)
                   Book element = (Book) iter.next();
                   System.out.println(element);
              System.out.println("delete a book");
              em.remove(book2);
              System.out.println("List all books");
               allBooks = em.createQuery("from Book").getResultList();
              for (Iterator iter = allBooks.iterator(); iter.hasNext();)
                   Book element = (Book) iter.next();
                   System.out.println(element);
    }BookTestBeanLocal.java
    package de.laliluna.library;
    import javax.ejb.Local;
    @Local
    public interface BookTestBeanLocal {
         public void test();     
    }BookTestBeanRemote.java
    package de.laliluna.library;
    import javax.ejb.Remote;
    @Remote
    public interface BookTestBeanRemote {
         public void test();
    }client part--> FirstEJB3TutorialClient.java
    package de.laliluna.library;
    import java.util.Properties;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import de.laliluna.library.BookTestBean;
    import de.laliluna.library.BookTestBeanRemote;
    * @author hennebrueder
    public class FirstEJB3TutorialClient {
          * @param args
         public static void main(String[] args) {
               * get a initial context. By default the settings in the file
               * jndi.properties are used. You can explicitly set up properties
               * instead of using the file.
                Properties properties = new Properties();
                properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
                properties.put("java.naming.factory.url.pkgs","=org.jboss.naming:org.jnp.interfaces");
                properties.put("java.naming.provider.url","localhost:1099");
              Context context;
              try {
                   context = new InitialContext(properties);
                   BookTestBeanRemote beanRemote = (BookTestBeanRemote) context
                             .lookup(BookTestBean.RemoteJNDIName);
                   beanRemote.test();
              } catch (NamingException e) {
                   e.printStackTrace();
                    * I rethrow it as runtimeexception as there is really no need to
                    * continue if an exception happens and I do not want to catch it
                    * everywhere.
                   throw new RuntimeException(e);
    }I have created persistance.xml and application.xml under META-INF folder.
    persistance.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence>
    <persistence-unit name="FirstEjb3Tutorial">
    <jta-data-source>hsqldb-db</jta-data-source>
    <properties>
    <property name="hibernate.hbm2ddl.auto"
    value="create-drop"/>
    </properties>
    </persistence-unit>
    </persistence>application.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd">
         <display-name>Stateless Session Bean Example</display-name>
         <module>
              <ejb>FirstEjb3Tutorial.jar</ejb>
         </module>
    </application>and in hsqldb-ds i have configured the driver and connection
    <datasources>
       <local-tx-datasource>
          <!-- The jndi name of the DataSource, it is prefixed with java:/ -->
          <!-- Datasources are not available outside the virtual machine -->
          <jndi-name>ejb3ProjectDS</jndi-name>
          <!-- For server mode db, allowing other processes to use hsqldb over tcp.
          This requires the org.jboss.jdbc.HypersonicDatabase mbean.
          <connection-url>jdbc:hsqldb:hsql://${jboss.bind.address}:1701</connection-url>
          -->
          <!-- For totally in-memory db, not saved when jboss stops.
          The org.jboss.jdbc.HypersonicDatabase mbean is required for proper db shutdown
          <connection-url>jdbc:hsqldb:.</connection-url>
          -->
          <!-- For in-process persistent db, saved when jboss stops.
          The org.jboss.jdbc.HypersonicDatabase mbean is required for proper db shutdown
          -->
         <!-- <connection-url>jdbc:hsqldb:${jboss.server.data.dir}${/}hypersonic${/}localDB</connection-url-->
         <connection-url>jdbc:hsqldb:data/tutorial</connection-url>
          <!-- The driver class -->
          <driver-class>org.hsqldb.jdbcDriver</driver-class>
          <!-- The login and password -->
          <user-name>sa</user-name>
          <password></password>
          <!--example of how to specify class that determines if exception means connection should be destroyed-->
          <!--exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.DummyExceptionSorter</exception-sorter-class-name-->
          <!-- this will be run before a managed connection is removed from the pool for use by a client-->
          <!--<check-valid-connection-sql>select * from something</check-valid-connection-sql> -->
          <!-- The minimum connections in a pool/sub-pool. Pools are lazily constructed on first use -->
          <min-pool-size>5</min-pool-size>
          <!-- The maximum connections in a pool/sub-pool -->
          <max-pool-size>20</max-pool-size>
          <!-- The time before an unused connection is destroyed -->
          <!-- NOTE: This is the check period. It will be destroyed somewhere between 1x and 2x this timeout after last use -->
          <!-- TEMPORARY FIX! - Disable idle connection removal, HSQLDB has a problem with not reaping threads on closed connections -->
          <idle-timeout-minutes>0</idle-timeout-minutes>
          <!-- sql to call when connection is created
            <new-connection-sql>some arbitrary sql</new-connection-sql>
          -->
          <!-- sql to call on an existing pooled connection when it is obtained from pool
             <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
          -->
          <!-- example of how to specify a class that determines a connection is valid before it is handed out from the pool
             <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.DummyValidConnectionChecker</valid-connection-checker-class-name>
          -->
          <!-- Whether to check all statements are closed when the connection is returned to the pool,
               this is a debugging feature that should be turned off in production -->
          <track-statements/>
          <!-- Use the getConnection(user, pw) for logins
            <application-managed-security/>
          -->
          <!-- Use the security domain defined in conf/login-config.xml -->
          <security-domain>HsqlDbRealm</security-domain>
          <!-- Use the security domain defined in conf/login-config.xml or the
               getConnection(user, pw) for logins. The security domain takes precedence.
            <security-domain-and-application>HsqlDbRealm</security-domain-and-application>
          -->
          <!-- HSQL DB benefits from prepared statement caching -->
          <prepared-statement-cache-size>32</prepared-statement-cache-size>
          <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
          <metadata>
             <type-mapping>Hypersonic SQL</type-mapping>
          </metadata>
          <!-- When using in-process (standalone) mode -->
          <depends>jboss:service=Hypersonic,database=localDB</depends>
          <!-- Uncomment when using hsqldb in server mode
          <depends>jboss:service=Hypersonic</depends>
          -->
       </local-tx-datasource>
       <!-- Uncomment if you want hsqldb accessed over tcp (server mode)
       <mbean code="org.jboss.jdbc.HypersonicDatabase"
         name="jboss:service=Hypersonic">
         <attribute name="Port">1701</attribute>
         <attribute name="BindAddress">${jboss.bind.address}</attribute>    
         <attribute name="Silent">true</attribute>
         <attribute name="Database">default</attribute>
         <attribute name="Trace">false</attribute>
         <attribute name="No_system_exit">true</attribute>
       </mbean>
       -->
       <!-- For hsqldb accessed from jboss only, in-process (standalone) mode -->
       <mbean code="org.jboss.jdbc.HypersonicDatabase"
         name="jboss:service=Hypersonic,database=localDB">
         <attribute name="Database">localDB</attribute>
         <attribute name="InProcessMode">true</attribute>
       </mbean>
    </datasources>.
    Edited by: bhanu on Dec 2, 2008 9:45 AM

    Hi jadespirit ,
    I have the same problem in the same Book example ,my ejb3 project name "BaseHotele" so i follow what u said and this is my persistence.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence>
    <persistence-unit name="FirstEjb3Tutorial">
    *<jta-data-source>java:BaseHoteleDS</jta-data-source>*
    <properties>
    <property name="hibernate.hbm2ddl.auto"
    value="create-drop"/>
    </properties>
    </persistence-unit>
    </persistence>
    But it didn't work i have always HotelTestBean not bound!!
    Help PLEASE i think that i had a mistake in the persistence.xml:i have 2 days searching for solutions without a good result!!!!!!!!!!!!!

  • 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

  • JMS Sender with ejb3 container managed transaction

    Hi all,
    I refer to the following link http://download.oracle.com/docs/cd/E11035_01/wls100/jms/trans.html#wp1035937
    I found that JTA support JMS.
    But I dont' want to use JTA explicitly, I want to use container manage transaction. eg. inside ejb3 stateless session bean.
    does it support JMS?
    With Regards,
    wp

    Hi,
    Yes, WebLogic JMS supports JTA (a.k.a XA, a.k.a global) transactions such as container managed transactions. There are two requirements for CMTs on SSB:
    (1) use an XML descriptor setting or EJB annotation to enable CMT for the SSB
    (2) use a WebLogic JMS connection factory that is configured to have "global (XA) transactions enabled"
    And I usually also recommend:
    (3) Consider using a JEE "res-ref" for the connection factory to enable pooling of JMS resources. See "Enhanced Support for Using WebLogic JMS with EJBs and Servlets" (http://download.oracle.com/docs/cd/E14571_01/web.1111/e13727/j2ee.htm#g1329180), and the "Integrating Remote JMS Providers" FAQ (http://download.oracle.com/docs/cd/E14571_01/web.1111/e13727/interop.htm#JMSPG553).
    (4) Avoid using SSBs to receive messages. MDBs are specifically designed for processing incoming messages.
    It's also possible to have WebLogic automatically enlist foreign (non-WebLogic) vendors in WebLogic transactions. See the "Integrating Remote JMS Providers" FAQ for details (http://download.oracle.com/docs/cd/E14571_01/web.1111/e13727/interop.htm#JMSPG553).
    Regards,
    tom

  • Application-Managed EntityManager transaction type must be RESOURCE_LOCAL

    [P-312 of Ejb3 In Action Book"] states:
    "For application-based EntityManager, the transaction-type must be set to RESOURCE_LOCAL in the persistence.xml file".
    but in case the application is running inside container (App server) , it can join JTA transaction. Sp why always transaction-type should be
    RESOURCE_LOCAL.?

    Because the section you took that from is 'Application-managed EntityManagers outside the Java EE Container'. So it would have to be RESOURCE_LOCAL as you are not running in the container (i.e. Java SE/Tomcat).
    If it is running inside a container then you could use JTA as the transaction type.
    m

  • Please hepl me. i m intergrating ejb3 and struts in two server. but is not working

    it is simple application i m runing in tow server but i m get classsnotfound error pleas solve my problem. i will give my direct structure of application
    i m runing ejb3 in weblogic 10.3 and struts in tomcat server. both communication is not happening pleas help me. i m try from many days. But is not working form me
    root dir
    onlyenb6
    account class
    package ejb3.onlyejb;
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    @Entity
    public class account implements Serializable{
    @Id
    int accno;
      public int getAccno() {
        return accno;
    public void setAccno(int accno) {
        this.accno = accno;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    public float getBalance() {
        return balance;
    public void setBalance(float balance) {
        this.balance = balance;
    String name;
    float balance;
    Int6_clss code
    package ejb3.onlyejb;
    import java.io.Serializable;
    public interface Int6_cls extends Serializable {
        public void storing(int acc, String name, float amt);
    Session.class code
    package ejb3.onlyejb;
    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    @Stateless(mappedName="saigoud")
    @Remote
    public class Session_ben implements Int6_cls {
        @PersistenceContext
        EntityManager mrg;
        public void storing(int acc, String name, float amt) {
    System.out.println("session="+acc);
    System.out.println("sess="+name);
            account accs=new account();
            accs.setAccno(acc);
            accs.setName(name);
            accs.setBalance(amt);
            mrg.persist(accs);
    build.xml
    <project name="onlyejb5" default="saifile">
    <property name="bea.home" value="C:/bea"/>
    <property name="wl_home" value="${bea.home}/wlserver_10.3"/>
    <path id="main.class.path">
    <pathelement path="${bea.home}/modules/com.bea.core.utils_1.4.0.0.jar"/>
    <pathelement path="${bea.home}/modules/com.bea.core.jarbuilder_1.2.0.0.jar"/>
    <pathelement path="${java.class.path}"/>
    </path>
    <target name="saifile">
    <echo message="***ANT Script should run from inside the ${wl.home}/server/lib *****" />
    <echo message="***** ********* ********* *****" />
    <java classname="com.bea.jarbuilder.JarBuilder">
    <classpath refid="main.class.path"/>
    <jvmarg value="-d ${wl.home}/server/lib -jar wljarbuilder.jar"/>
    </java>
    </target>
    </project>
    after run with ant i get successfully create wlfullclient.jar
    i m taking this wlfullclient.jar and pasting in tomcat lib directery and run webapplication
    my webapplication code
    package ejb3.onlyejb;
    import java.io.Serializable;
    public interface Int6_cls extends Serializable {
        public void storing(int acc, String name, float amt);
    package ejb3.onlywed;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Hashtable;
    import java.util.Properties;
    import javax.ejb.EJB;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import ejb3.onlyejb.Int6_cls;
    public class Action_cls extends Action {
            public ActionForward execute(ActionMapping map, ActionForm fm, HttpServletRequest req, HttpServletResponse res)
        throws IOException{
            String respkey="fails";
            Action_form_bean bean=(Action_form_bean)fm;
            int ac=bean.getAccno();
            String na=bean.getName();
            float bal=bean.getAmt();
            System.out.println("accno="+ac);
    System.out.println("na="+na);
    System.out.println("bal="+bal);
    System.out.println("enter in to if loop");
               Hashtable p=new Hashtable();
    p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    p.put(Context.PROVIDER_URL,"t3://localhost:7001");
            System.out.println("jndi properties nuderprocess");
               try {
    System.out.println("loading p file="+p);
                InitialContext ic = new InitialContext(p);
    System.out.println("loading p file over="+ic);
            System.out.println("jndi file is  loaded");
          //System.out.println("wrs="+wrs);
    System.out.println("entry in try block");
    Int6_cls wrs=(Int6_cls)ic.lookup("saigoud#ejb3.onlyejb.Int6_cls");
           System.out.println("lookup susfull");
              wrs.storing(ac, na, bal);
        respkey="ok";
              } catch (NamingException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
            catch (Exception e) {
                // TODO: handle exception
            ActionForward fw=map.findForward(respkey);
            return fw;
    get error
    accno=44
    na=hjhjhj
    bal=777.0
    enter in to if loop
    jndi properties nuderprocess
    jndi properties nuderprocess22
    loading p file={java.naming.provider.url=t3://localhost:7001, java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory}
    loading p file over=javax.naming.InitialContext@12f9bcd
    jndi file is  loaded
    entry in try block
    Jul 5, 2013 1:36:22 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet action threw exception
    java.lang.ClassNotFoundException: ejb3.onlyejb.Int6_cls
        at weblogic.ejb.container.deployer.RemoteBizIntfClassLoader.getClassBytes(RemoteBizIntfClassLoader.java:151)
        at weblogic.ejb.container.deployer.RemoteBizIntfClassLoader.loadClass(RemoteBizIntfClassLoader.java:96)
        at weblogic.ejb.container.internal.RemoteBusinessIntfGenerator.generateRemoteInterface(RemoteBusinessIntfGenerator.java:54)
        at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.readObject(RemoteBusinessIntfProxy.java:205)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1846)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
        at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1945)
        at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1869)
        at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
        at weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:197)
        at weblogic.rjvm.MsgAbbrevInputStream.readObject(MsgAbbrevInputStream.java:564)
        at weblogic.utils.io.ChunkedObjectInputStream.readObject(ChunkedObjectInputStream.java:193)
        at weblogic.rmi.internal.ObjectIO.readObject(ObjectIO.java:62)
        at weblogic.rjvm.ResponseImpl.unmarshalReturn(ResponseImpl.java:240)
        at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)
        at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:259)
        at weblogic.jndi.internal.ServerNamingNode_1030_WLStub.lookup(Unknown Source)
        at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:392)
        at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:380)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at ejb3.onlywed.Action_cls.execute(Action_cls.java:62)
        at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
        at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
        at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
        at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
        at java.lang.Thread.run(Thread.java:619)

    Locking multipost.

  • Some issues while testing EJB3 API

    I'm running some EJB3 peristence test outside standalone and I'm running
    into some issues that I did not see running the same code against the
    Hibernate EntityManager implementation.
    I'm currently using the Kodo 4.0EA3 download. Any help is appreciated.
    I have the following table:
    Table "public.beers"
    Column | Type | Modifiers
    id | integer | not null
    brand | character varying(50) |
    price | numeric(15,2) |
    Indexes:
    "beers_pkey" PRIMARY KEY, btree (id)
    With the following class:
    package com.springdeveloper.model;
    import javax.persistence.*;
    import java.io.Serializable;
    @Entity
    @Table(name="BEERS")
    public class Beer implements Serializable {
    private Long id;
    private String brand;
    private Double price;
    public Beer() {
    public Beer(Long id) {
    this.id = id;
    @Id(generate=GeneratorType.AUTO)
    @Column(name="ID", nullable=false)
    public Long getId() {
    return id;
    public void setId(Long id) {
    this.id = id;
    public String getBrand() {
    return brand;
    public void setBrand(String brand) {
    this.brand = brand;
    public Double getPrice() {
    return price;
    public void setPrice(Double price) {
    this.price = price;
    public String toString() {
    return "[" + id + "] " + brand + " " + price;
    Issues:
    =======
    1) If I don't have a column named type I get an error -
    Exception in thread "main" <2|false|4.0.0EA3> kodo.util.StoreException:
    ERROR: column t0.type does not exist {prepstmnt 14211340 SELECT t0.ID,
    t0.TYPE, t0.brand, t0.price FROM BEERS t0 WHERE (t0.ID = ?) [reused=0]}
    [code=0, state=42703]
    Any way around this since there is no inheritance structure involved?
    2) If I don't specify a fully qualified name for the first query I get
    this error:
    33 INFO [main] kodo.Runtime - Starting Kodo 4.0.0EA3
    74 DEBUG [main] kodo.Runtime - License capabilities: "Kodo Standard
    Edition,Kodo Community Edition,Kodo Evaluation Edition,Datacache Plug-
    in,Custom Result Object Providers,Custom Mappings,Enterprise
    Databases,Query Extensions,Performance Pack,Statement Batching,Kodo
    Enterprise Edition,Managed Environment,Developer Tools,Custom
    DBDictionaries" Expiration: "11/22/05 7:00 PM" Maintenance expiration:
    "11/22/05 7:00 PM"
    496 INFO [main] kodo.jdbc.JDBC - Using dictionary class
    "kodo.jdbc.sql.PostgresDictionary".
    1007 INFO [main] kodo.MetaData - Found 3 classes with metadata in 0
    milliseconds.
    Exception in thread "main" <4|false|4.0.0EA3>
    kodo.persistence.ArgumentException: Could not resolve entity named "Beer".
         at kodo.query.ejbql.EJBQLParser.populate(EJBQLParser.java:61)
         at kodo.query.ExpressionStoreQuery.populateFromCompilation
    (ExpressionStoreQuery.java:129)
         at kodo.query.QueryImpl.compileForCompilation(QueryImpl.java:682)
         at kodo.query.QueryImpl.compileForExecutor(QueryImpl.java:713)
         at kodo.query.QueryImpl.getOperation(QueryImpl.java:1624)
         at kodo.query.DelegatingQuery.getOperation(DelegatingQuery.java:136)
         at kodo.persistence.QueryImpl.execute(QueryImpl.java:231)
         at kodo.persistence.QueryImpl.getSingleResult(QueryImpl.java:258)
         at KodoTest.main(KodoTest.java:16)
    If I specify a fully qualified name for the EJBQL the first time I query
    then I can just use 'Beer' in subsequent queries. It doesn't help to
    specify '@Entity(name="Beer")' in the persistent class either.
    Here is my query:
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Beer b = (Beer)em.createQuery(
    "select object(o) from Beer o where o.id = :id")
    .setParameter("id", new Long(2))
    .getSingleResult();
    System.out.println("Beer: " + b);
    em.getTransaction().commit();
    This works but is kind of ugly:
    Beer b = (Beer)em.createQuery(
    "select object(o) from com.springdeveloper.model.Beer o where
    o.id = :id")
    .setParameter("id", new Long(2))
    .getSingleResult();
    And here is my peristence.xml:
    <?xml version="1.0"?>
    <entity-manager>
    <name>BeerDistributor</name>
    <provider>kodo.persistence.PersistenceProviderImpl</provider>
         <properties>
              <!--
              To evaluate or purchase a license key, visit http://
    www.solarmetric.com
              -->
              <property name="kodo.LicenseKey" value="????-????-????-????-????"/>
    <property name="kodo.PersistentClasses"
    value="com.springdeveloper.model.Beer,
    com.springdeveloper.model.Customer,
    com.springdeveloper.model.Order"/>
    <!--
    Connection configuration.
    -->
              <property name="kodo.ConnectionURL" value="jdbc:postgresql://
    localhost/test"/>
              <property name="kodo.ConnectionDriverName"
    value="org.postgresql.Driver"/>
              <property name="kodo.ConnectionUserName" value="trisberg"/>
              <property name="kodo.ConnectionPassword" value="????"/>
              <!--
              To disable logging, set value to 'none'.
              To use Log4J, configure Log4J appropriately, and set value to
    'log4j'.
              To view trace of all SQL being executed, add 'SQL=TRACE' to value
    below.
              -->
              <property name="kodo.Log" value="DefaultLevel=INFO, Runtime=DEBUG,
    Tool=INFO"/>
         </properties>
    </entity-manager>
    Thanks,
    Thomas Risberg

    1) If I don't have a column named type I get an error -This, unfortunately, is something that we need to clarify in the spec
    itself. Currently, the discriminator value and column for a class have
    default values in the spec. So technically, every base class has a
    discriminator column according to spec defaults.
    Obviously this isn't practical. In fact Kodo already turns off
    automatic discriminator columns for vertical and table-per-class
    inheritance unless you explicitly give a discrimintor value or column.
    So one way to not use a discriminator column in Kodo right now is to set
    your inheritance type to JOINED or TABLE_PER_CLASS. Another way is to
    use Kodo's kodo.persistence.jdbc.DiscriminatorStrategy annotation, which
    allows you to name a non-standard or custom discriminator strategy.
    Setting this annotation's value to "final" (an alias for Kodo's
    kodo.jdbc.meta.strats.NoneDiscriminatorStrategy) will indicate that the
    class doesn't need a discriminator because it won't be extended.
    We will try to get this ironed out in future versions of the spec.
    If I specify a fully qualified name for the EJBQL the first time I query
    then I can just use 'Beer' in subsequent queries. It doesn't help to
    specify '@Entity(name="Beer")' in the persistent class either.This sounds like a bug in our early access implementation. I have a
    feeling it only occurs with property access entities -- if you change
    your entity to use field access (which also means using Kodo
    enhancement), I think you'd see the problem go away. I think it might
    also go away if you performed some other persistence operation on a Beer
    entity (such as a by-id lookup) before attempting the query. We'll make
    sure to have this fixed for our next release. Thanks for the report.

  • EJB3: One-to-one relationships and auto-generation of primary key values...

    Dear Forum,
    I'm relatively new to JEE, and while I've so far enjoyed the convenience of EJB3 for most things, it seems that I have a corner case that can not be handled by the entity manager.
    First, here's a quick mockup of my entities:
        Gallery
                |
                -- [1] -------[1] ----> Author
                |
                -- [1] -------[M] ---> Photo
                                                  |
                                                  -- [1] ------ [1] -> PhotoImage
                                                                                     |
                                                                                     -- [1] ------ [1] -> IPTCData
                                                                                     |
                                                                                     -- [1] ------ [1] -> EXIFDataI also have a remote, stateless session bean that does nothing more than persist()/merge()/remove() and locate (through find() and a few custom queries) my Gallery and Photo instances.
    Now, the abridged version of my problem is this: when I persist a Photo, it naturally gets its primary key generated (I used @Id and @GeneratedValue). However, for some reason none of the other dependent entities inherit Photo's primary key value. In my client, I create a new Gallery locally and then persist it. I then create new Photo, PhotoImage, IPTCData and EXIFData instances. I add the IPTCData and EXIFData instances to PhotoImage (there are PhotoImage methods for adding those); then I add the PhotoImage instance to Photo (again, Photo has a setter for adding a PhotoImage). Then, I persist the Photo.
    --- Aside: ------------
    I've set up my relationships using annotations like @OneToMany (Gallery references a Collection of Photos), and @OneToOne (Photo's primary key references PhotoImage's primary key; PhotoImage's primary key references the primary keys of IPTCData and EXIFData). I've also added @JoinColumn annotations where necessary.
    Finally, I get the Gallery instance's Photo collection (public Collection<Photo> getPhotos()), I add the Photo to the collection, and I add the Photo collection BACK to the Gallery (public void setPhotos(Collection<Photo>)).
    At this point, the Gallery should have all of my entities contained inside of itself. However, when I persist the Gallery at this point, all of the entities show up in the database, but none of the primary keys get inherited. Photo's primary key gets generated automatically, of course, but the rest have zero (0) as their PK values. I had wanted, for example, IPTCData to get the value of Photo.id.
    I had assumed that the entity manager would persist everything for me provided that I told it, through my annotations, about which entities relate to which. Does persistence only work in the direction of retrieval? That is, does the entity manager only do its thing when fetching (versus setting) data when there is more than 1 object in the graph? I can't believe that it can't, otherwise we'd all be ditching it and going back to straight SQL to do our work.
    Thus, I HAVE to be doing something wrong, or else omitting to do something right.
    I've made other incarnations of the above setup, and none of them have worked perfectly. I've even set up foreign key constraints in the database, but I had my share of unresolvable problems there, too.
    So I guess my big question with all of this is: when you have a deeply nested graph of objects, can the entity manager figure everything out and persist all of the objects correctly and with the right values? If not, boo. If so, how does one accomplish this?
    I know that I could persist each and every entity separately in my client code, but I wanted to have a natural-looking way of piecing all of my entities together. More specifically, I could persist IPTCData explicitly; however, I want to be able to add everything to a Photo and only persist the Photo itself, with the idea that all of the objects and sub-objects would be persisted automagically.
    Is this possible? Or have I bought into a pipe dream with the guarantee of the proverbial magic bullet?
    Thanks to everyone in advance for his/her input.
    Regards,
    Michael

    Daniel,
    Late last night I found the solution to my problem. And you're right, it had everything to do with which side is wired to which. I got confused about which side to consider the "owning" side, since one can look at it from the perspective of the database or the application.
    Interestingly, the first 2 lines of your example code match my client code almost verbatim: First, I create a new Gallery (or else I get an existing one). I then create a new Photo and then add it to the Gallery's collection using add(). I then persist the Gallery. My session bean internally calls EntityManager.merge(gallery). How it differs from your example, though, is in the fact that, on an application level, a Photo has no knowledge whatsoever of a Gallery. Which is to say that my Photo class does not have a 'getGallery()' method. Somehow, Hibernate is able to figure it all out and still update Photo's 'parentIdRef' column in the database. My logs show that Hibernate issues a SQL UPDATE on the Photo after both a Gallery and a Photo have been created. It sets the Photo's 'parentIdRef' column to the primary key value of the owning Gallery.
    Getting back to the matter, my problem was not with being able to map a Photo to a Gallery; rather, I was unable to add a PhotoImage to a Photo and have the relationship get correctly mapped in the database. The relationship between a Photo and a Gallery is many-to-one: there can be many Photo objects inside of a Gallery. In the database, a Photo row contains a 'parentIdRef' column whose value is that of a Gallery's primary key. I used @OneToMany on the Gallery, since a Gallery is, from an application perspective, the "owning" side, even though it's only the Photo that knows who it's referring to since only IT contains the 'parentIdRef' column in the database.
    I tried setting up the relationship between a PhotoImage and a Photo in the same manner, with the PhotoImage having a 'parentIdRef' column and referring to a Photo's primary key. I had annotated the Photo's getPhotoImage() method with @OneToOne, along with an appropriate @JoinColumn.
    It was THIS part that I had backwards. With a @OneToMany relationship, the child refers back to the parent --- it can be no other way. However, with a @OneToOne relationship, the owner refers to the child.
    So, to make a long story short, all I had to do was create extra database columns for Photo. Those columns refer to the primary keys of PhotoImage, EXIFData and IPTCData. Concretely, for example, Photo.photoImageIdRef references PhotoImage.id. And so on and so forth.
    The only negative side-effect of this is that my database-level foreign key constraints are now broken, since Hibernate wants to persist PhotoImage, EXIFData and IPTCData before it persists Photo.
    I have to investigate more deeply the 'cascade=...' option of the @OneToOne annotation in order to find out it relates, if at all, to a database-level cascade.
    Anyway, thanks for the reply. It seems that you had a very good idea about what my problem was. I would have posted the fact that I had resolved the problem last night, except that it was too late and I was heading to bed. If you still want the Duke points, let me know. I don't currently know the rules about if, when and to whom I should issue points in cases like these when I've already solved the problem.
    Regards,
    Michael

  • How to call oracle function from ejb3

    i'm trying to call an oracle query-function from ejb3.
    The oracle function:
    create or replace FUNCTION getSecThreadCount(secId in NUMBER,avai in NUMBER)
    RETURN SYS_REFCURSOR is cur SYS_REFCURSOR;
    m_sql VARCHAR2(250);
    BEGIN
    m_sql:='select count(thrId) from thread where secId='|| secid||'
    and thrAvai='|| avai;
    open cur for m_sql;
    return cur;
    END;
    I'v tried several ways to call it,but all failed:
    1. the calling code:
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNativeQuery("{call getSecThreadCount(?,?) }");     
              query.setParameter(1, secId);
              query.setParameter(2, avai);
              return query.getSingleResult();
    but i got the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: ORA-06550: row 1, col 7:
    PLS-00221: 'GETSECTHREADCOUNT' not procedure or not defined
    ORA-06550: row 1, col 7:
    PL/SQL: Statement ignored
    2. the calling code:
    @SqlResultSetMapping(name = "getSecThreadCount_Mapping")
    @NamedNativeQuery(name = "getSecThreadCount",
    query = "{?=call getSecThreadCount(:secId,:avai)}",
    resultSetMapping = "getSecThreadCount_Mapping",
    hints = {@QueryHint(name = "org.hibernate.callable", value = "true"),
              @QueryHint(name = "org.hibernate.readOnly", value = "true")})
    public Object getSectionThreadCount(int secId,int avai){
              Query query=manager.createNamedQuery("getSecThreadCount");     
              query.setParameter("secId", secId);
              query.setParameter("avai", avai);
              return query.getSingleResult();
    but i run into the exception:
    Exception in thread "main" javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query; nested exception is: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
    Caused by: java.sql.SQLException: lost in index IN or OUT parameter:: 3
    By the way, i have successfully called the function from hibernate. And i use oracle 11g, JBoss5 RC1.
    Could anyone tell me how to call the function from EJB3?
    Thanks.

    Here's a working model:
    package.procedure: (created in example schema scott)
    CREATE OR REPLACE package  body data_pkg as
      type c_refcursor is ref cursor;
      -- function that return all emps of a certain dept
      function getEmployees ( p_deptId in number
      return c_refcursor
      is
        l_refcursor c_refcursor;
      begin
         open l_refcursor
        for
              select e.empno as emp_id
              ,        e.ename as emp_name
              ,        e.job   as emp_job
              ,        e.hiredate as emp_hiredate
              from   emp e
              where  e.DEPTNO = p_deptId;
        return l_refcursor;
      end getEmployees;
    end data_pkg;
    /entity class:
    package net.app.entity;
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.QueryHint;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;
    @SuppressWarnings("serial")
    @Entity
    @Table (name="emp")
    @SequenceGenerator(name = "EmployeeSequence", sequenceName = "emp_seq")
    @NamedNativeQuery( name = "getEmpsByDeptId"
                   , query = "{ ? = call data_pkg.getEmployees(?)}"
                   , resultClass = Employee.class
                   , hints = { @QueryHint(name = "org.hibernate.callable", value = "true")
                          , @QueryHint(name = "org.hibernate.readOnly", value = "true")
    public class Employee implements Serializable
        @Id
        @Column(name="emp_id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EmployeeSequence")
        private int id;
        @Column(name="emp_name")
        private String name;
        @Column(name="emp_job")
        private String job;
        @Column(name="emp_hiredate")
        private Date hiredate;
        // constructor
        public Employee (){}
        // getters and setters
        public int getId()
         return id;
    etc...session bean:
    package net.app.entity;
    import java.util.ArrayList;
    import java.util.List;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    @Stateless
    public class ScottAdminImpl implements ScottAdmin
        @PersistenceContext
        private EntityManager entityManager;
        @SuppressWarnings("unchecked")
        public List<Employee> getEmployeesByDeptId(int deptId)
         ArrayList<Employee> empList;
         try
             Query query = entityManager.createNamedQuery("getEmpsByDeptId");
             query.setParameter(1, deptId);
             empList = (ArrayList<Employee>) query.getResultList();
             return empList;
         catch (Exception e)
             e.printStackTrace(System.out);
             return null;
    }client:
    package net.app.client;
    import java.util.List;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import net.app.entity.Employee;
    import net.app.iface.ScottAdmin;
    public class ScottClient
        public static void main(String[] args)
         try
             // create local interface
             InitialContext ctx = new InitialContext();
             ScottAdmin adminInterface = (ScottAdmin) ctx.lookup("ScottAdminImpl/remote");
             // select employees by deptno
             int deptno = 20;
             List<Employee> empList = adminInterface.getEmployeesByDeptId(deptno);
             // output
             System.out.println("Listing employees:");
             for (Employee emp : empList)
              System.out.println(emp.getId() + ": " + emp.getName() + ", " + emp.getJob() + ", " + emp.getHiredate());
         catch (NamingException e)
             e.printStackTrace(System.out);
    }Basically you just ignore the refcursor outbound parameter.
    This is a stored function, have yet to try outbound refcursor parameters in stored procedures...
    Edited by: _Locutus on Apr 2, 2009 2:37 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • EJB3 CORRUPTED when using more than one PersistenceUnit

    Hi,
    I am using JSF, EJB3 on Glassfish. CMP and JTA.
    This is the scenario:
    A user logs into application choosing one Persistence Unit (like in JavaSE). This is only at the beginig as I want to use Glassfish CMP and JTA.
        public EntityManagerFactory getEmf() throws Exception {
            configOverrides = new HashMap<String,Object>();
            configOverrides.put(TARGET_DATABASE,TargetDatabase.SQLServer);
            configOverrides.put(TARGET_SERVER,TargetServer.SunAS9);
            configOverrides.put(JTA_DATASOURCE,"jdbc/"+puName);
            configOverrides.put(SESSION_NAME,puName+"_session");
            emf = Persistence.createEntityManagerFactory(puName,configOverrides);
            return emf;
        }I then put the corresponding PersistenceUnit name in http Session scope to be used later on.
    I created a CommonEjbImpl to further inject via Jndi (and therefore use CMP and JTA) an EntityManger in each EJB3 as follows:
    @PersistenceContexts({
       @PersistenceContext(name="pu/SOCIETE1", unitName="SOCIETE1"),
       @PersistenceContext(name="pu/SOCIETE2", unitName="SOCIETE2"),
       @PersistenceContext(name="pu/SOCIETE3", unitName="SOCIETE3"),
       @PersistenceContext(name="pu/SOCIETE4", unitName="SOCIETE4"),
       @PersistenceContext(name="pu/SOCIETE5", unitName="SOCIETE5"),
       @PersistenceContext(name="pu/GENESYS_EXEMPLE", unitName="GENESYS_EXEMPLE")
    public class CommonEjbImpl {
        public EntityManager initEm() {
            LogUtil.log(this.getClass(),(String)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("database"));
            return initEm((String)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("database"));   
        public EntityManager initEm(String puName) {
            EntityManager em = null;
            try {
                em = (EntityManager) new InitialContext().lookup("java:comp/env/pu/"+puName);
            } catch (NamingException ex) {
                LogUtil.error(this.getClass(),ex);
            return em;   
        public void cleanup(EntityManager em) {
            //LogUtil.log(this.getClass(), "CLEANING EJB..with em: "+em);
            if (em != null && em.isOpen()) {
                em.close();
        } And in each EJB3, I use this CommonEjBImpl to get the Entity Manager like this:
    @Stateless
    public class TreeEJB extends CommonEjbImpl implements TreeEJBLocal {
        public TreeEJB() {
        private EntityManager em;
        @PostConstruct
        public void init() {
            em = super.initEm();
        @PreDestroy
        public void cleanup() {
            super.cleanup(em);
    }I have also a JSF backing bean (in SESSION SCOPE) "TreeBean" in which i Inject an EJB3 like this:
        <managed-bean>
            <managed-bean-name>TreeBean</managed-bean-name>
            <managed-bean-class>com.mfpsoft.bean.tree.TreeBean</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>and:
    public class TreeBean extends BeanLoader {
        public TreeBean() {
        @EJB
        private TreeEJBLocal treeEJB;
        @PostConstruct
        public void init() {
            treeEJB.init();
    }SO, imagine what is happening:
    USER1 logs (a persistence unit)
    USER2 logs (a different persistence unit)
    USER1 refresh tree for example
    USER2 rehresh tree also
    ==> USER2 GETS data from USER1 persitence unit
    My questions:
    EJB3 refrence seems to in application scope. Is thereonly one EJB3 refrence per appication?
    If so, how can I use same EJB with different persistence COntexts at the same time.
    Would this be a workaround ?? get entityManager at each business method of the EJB like this
        public  Object Method(Object object) throws Exception {
            EntityManager em = super.initEm();
            try {
                ...//em operations
            } catch (Exception ex) {
            } finally {
               em.close();
        }Would the data be corrupted if simultaneous access to same method by diffrent users?
    This issue is quite URGENT
    I would really appreciate a quick help on this
    Many thanks in advance
    Nicog

    Hi Zsom,
    Thanks for your answer
    Let me explain more clearly.
    My architecture is as follows: using JSF, Glassfish and ...SQL Server!! (! i know but this is mandatory requirement as our application is full web version of an existing ERP application already sold and installed by more than 1000 of our customers...
    I am using
    JSF-->JSF Managed Bean (Session for some and Request for almost all when logged )-->EJB Interface-->EJB Impl-->Entity-->Database
    Our application is ERP that our customers uses to managed several companies simultanously .
    This product ,mainly for intranets, is delivered with glassfish, the web application and SQL server containing by default 5 databases SOCIETE1,...SOCIETE5...but more can be created by our consultants for this customer....
    All databases have the same schema but not the same data.
    Sincerely, if I had done the desgin of the database, for sure I would have put all SOCIETEn in one DB but this is historical and I cant do anything against it.
    You have to see in our case, a database as a company of our customer (a joint venture for instance), each of which  with particular configuration, customers, orders, invoices, contacts....
    I have a persistence Unit (using JTA and CMP) per database , each using a connection pool managed by Glassfish.
    At the login of my application, the user (a user of our cutomer that bought this product), choose a database (a company actually lets say SOCIETE1), ...enter logging info and connect.
    The user must also be able to launch another browser window and connect lets say to SOCIETE2, and then work on SOCIETE1 AND SOCIETE2 simultanously.
    Also, I need Session Scope as there is configuration data that I need to keep over all pages. This configuration data is depending on the database connected to and the user.
    A session is therefore linked to the pair USER+DATABASE
    When selecting the database (company) for combo in logging form, the only way I found is fisrt to check if database(company) exists and can be connect to using at first begining Persistence.CreateEntityMangerFactory.. (i know that this is not J2EE and CMP but merly used in Java SE environments..).
    This step is only used for checking database.
    Then, if creation did not generate a Persistence Exception , I can use CMP and an EnityManger in EJB by JNDI lookup (as DI is not possible because you need constant in unitName);
    Doing so, the EJB (which only handles actions on Entities) manage the entities of the corresponding company SOCIETE1 or SOCIETE2, or.....
    I know that I might use antipatterns here, but actually this is the only solution I found
    Would an extra Layer between JSF bean and EJB do the trick....if yes how to inject the good persistence unit in my EJB is still in question.
    More if one Persistence unit is injected (assuming EJB being stateless) and another user working on another persistence unit is using the same EJB, then I go back in my first message on this topic
    As the number of databases for a customer is unknown, I can not create an EJB par database (lets says EJB_SOCIETE1, EJB_SOCIETE2,...). I agree that in this case they would be stateless....
    Do you have any suggestion to repect patterns in this situation.
    This would be greatly appreciated
    Thanks again
    Nicolas

Maybe you are looking for