EJB: Object not found exception

Posted on 2006-03-23
Last Modified: 2013-12-22
I have a servlet which is communicating with a couple of EJB's which include both session and entity beans. When I run the program it seems to run for six records and then throws up an "javax.ejb.ObjectNotFoundException: Bean not found in ................"

My program is;

public class NewsletterTestServlet extends HttpServlet
    private static Logger log = Logger.getLogger(NewsletterTestServlet.class);

     * Loop through all newsletters. Get office for each newsletter.  Get all users of that office
     * who are subscribed and send them the email
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        EmailGenerator emailGenerator = new EmailGenerator();
        InputStream newsletterStream  = request.getSession().getServletContext().getResourceAsStream(
            int newsbastsuccess = 0;

            EcpPortalSessionLocal epsl = (EcpPortalSessionLocal) request.getSession().getAttribute(

            // Get all custom newsletters and iterate
            String unsubscribeUrlBase = "http://" + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath() + "/servlet/";
            //Collection newsletters = CustomNewsletterTypeUtil.getLocalHome().findAll();
            Connection con = AcuvueFunctions.getConnection();
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery(new StringBuffer("SELECT cn.CUSTOMNEWSLETTERPK, nm.MESSAGE, cn.CREATIONDATE, ot.OFFICEPK ,ot.OFFICENAME, nt.SUBSCRIPTIONPK, nt.NEWSLETTERNAME, ")
                  .append("       NVL(cat.ADDRESS1, ' ') ADDRESS1, NVL(cat.ADDRESS2, ' ') ADDRESS2, NVL(cat.SUITE, ' ') SUITE, ")
                  .append("       NVL(cat.CITY, ' ') CITY, NVL(cat.STATE, ' ') STATE, NVL(cat.ZIPCODE, ' ') ZIPCODE, ")
                  .append("       DECODE(NVL(cet.ISPUBLIC, 0), 1, EMAILADDRESS, 'PRIVATE')  EMAILADDRESS, ")
                  .append("       DECODE(NVL(cpt.ISPUBLIC, 0), 1, PHONENUMBER, 'PRIVATE') PHONENUMBER ")
                  .append("  FROM CUSTOMNEWSLETTER cn, ")
                  .append("       NEWSLETTERMESSAGE nm, ")
                  .append("       NEWSLETTERTYPE nt, ")
                  .append("       OFFICETYPE ot, ")
                  .append("       CONTACTADDRESSTYPE cat, ")
                  .append("       CONTACTEMAILTYPE cet, ")
                  .append("       CONTACTPHONETYPE cpt ")
                  .append(" WHERE cn.CUSTOMMESSAGE = nm.NEWSLETTERMESSAGEPK AND ")
                  .append("       nm.NEWSLETTERPK = nt.NEWSLETTERPK AND ")
                  .append("       cn.OFFICEPK = ot.OFFICEPK AND ")
                  .append("       ot.emailpk = cet.emailpk (+) AND ")
                  .append("       ot.phonepk = cpt.phonepk (+) AND ")
                  .append("       ot.ADDRESSPK = cat.ADDRESSPK (+)").toString());

                        while (
                        { // Start of loop
                              String office = rs.getString("OFFICEPK");
      System.out.println("Office pk recvd :***"+ office);

                              // Get all users for this office and
                              // see if user is subscribed to the newsletter

      System.out.println("Inside while here 1");
                              Collection users = UserTypeUtil.getLocalHome().findByOffice(office);
      System.out.println("Inside while here 2");

                    "Found " + users.size() + " users");
      System.out.println("The no: of users for this office :****"+users.size());
                              Iterator usersIter = users.iterator();
                              while (usersIter.hasNext())
                              { // Inner loop
                                    UserTypeLocal userLocal = (UserTypeLocal);
                                    UserTypeLocalValue user = userLocal.getUserTypeLocalValue();
                                    Collection subscriptions = UserSubscriptionTypeUtil.getLocalHome().findUserSubscriptionTypeLocalsByUser(user.getPrimaryKey());
                           + " has " + subscriptions.size() + " subscriptions");
      System.out.println("The no. of Subscriptions are : ***"+ subscriptions.size() );
                                    Iterator it = subscriptions.iterator();
                                    // See if user is subscribed to the newsletter
                                    { // Second inner loop
                                          UserSubscriptionTypeLocal ustl = (UserSubscriptionTypeLocal);
                                          UserSubscriptionTypeLocalValue userSub = ustl.getUserSubscriptionTypeLocalValue();
      System.out.println("Inside second while here 3");

                                          if (AcuvueEJBConstants.UserSubscriptionStatusSubscribed.equals(userSub.getStatus())
                                                      && rs.getString("SUBSCRIPTIONPK").equals(userSub.getSubscriptionTypeLocalValue().getPrimaryKey()))
      System.out.println("The Subscribed user is:****"+ user);

                                                String unsubscribeUrl = unsubscribeUrlBase + "userpk=" + user.getPrimaryKey()
                                                                                    + "&newsletterpk=" + rs.getString("CUSTOMNEWSLETTERPK");
                                                //Create email and send
                                                String commid = emailGenerator.generateNewsletterEmail(
                                                                        unsubscribeUrl );

                                       "Sending-" + commid);
                        } // End of While(
                  }// End of inner try
                  catch(Exception e)
                        System.out.println("Exception in office record in whiles: ***"+ e);
                  newsbastsuccess = 1;
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        String url = "/secure/admin/newsletter_error.jsp";
        if ( newsbastsuccess == 1 ) {
            url = "/secure/admin/newsletter_sent.jsp";

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( url ) ;
        dispatcher.forward(request, response);

The Exception thrown is;
javax.ejb.ObjectNotFoundException: Bean not found in 'findByOfficeType....................'

Appreciate your help on this.

Best Regards
Question by:M_SYED
    LVL 8

    Expert Comment

    by:Leo Eikelman
    Is your Bean associated with a package name?

    And where is your bean located?

    It should be in WEB-INF/classes/"BeanClassName".java

    and when you package it , it should be in


    Hope this helps,


    LVL 5

    Expert Comment

    The office type that you are passing, does this have valid entries in the database. If not then the exception will be thrown. No exception if the office type returns more than one row.
    LVL 5

    Expert Comment


    The javadocs say

    "The ObjectNotFoundException exception is thrown by a finder method to indicate that the specified EJB object does not exist.

    Only the finder methods that are declared to return a single EJB object use this exception. This exception should not be thrown by finder methods that return a collection of EJB objects (they should return an empty collection instead).

    So you should be getting an empty collection for the same.

    One more thing, you said it runs for 6 records, then the exception comes.
    Does this mean in one go, the iterations go for 6 loops and then the error.
    Six times the method is called successfully nd then the error .

    Author Comment


    mrigank: The method calls are in a while loop which runs for each record retrieved from the database.
    The error comes for a specific record after the same piece of code has been executed six times, this code includes method calls too.

    I hope that answers your question.

    I am thinking that it might be a data quality issue, because the program works for most of the records apart from a few which are causing the error.

    Thanks a lot for your posts experts. Appreciate them.
    LVL 5

    Expert Comment

    Try deleting those records from the db and running the program and see if the error recurs.
    LVL 8

    Accepted Solution

    Is your findByOffice method using getBean(int i) method anywhere in your code?

    If you are, try using getBean() instead of getBean(int i)

    I don't really see any problem with the code itself.




    Author Comment

    I think so too. Let me verify the quality of the data in the record thats throwing the error.

    Author Comment

    I am using getBean() in the code and not getBean(int i)

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Java/J2EE and SOA

    This course will cover both core and advanced Java concepts like Database connectivity, Threads, Exception Handling, Collections, JSP, Servlets, XMLHandling, and more. You'll also learn various Java frameworks like Hibernate and Spring.

    Suggested Solutions

    Title # Comments Views Activity
    Conflicting setter definitions for property Exception 5 38
    tenRun challenge 28 67
    squareUp  challenge 22 80
    bunnyEars2 challenge 6 46
    After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
    Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
    This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
    This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now