Discussions

EJB programming & troubleshooting: Duplicate Entity Bean creation

  1. Duplicate Entity Bean creation (1 messages)

    Folks, I have a Stateless Session Bean that has a method like the following:

    public void method(String name) {

        try {
            EntityA a = entityAHome.findByName(name);
        }
        catch(ObjecctNotFoundException e) {

             // Do some processing

              entityAHome.create(name);
         }
    }


    I think my problem is that after the "findByName" fails and goes into the exception, but _before_ it does the create -- another thread comes along and does the same "findByName", which fails, so now there are two threads that will execute the create method. This results in two instances of EntityA with the same "name".

    How does one get around this problem?

    Thanks!
  2. Duplicate Entity Bean creation[ Go to top ]

    Make the name field a unique field or a primary key in your database. This will prevent duplicate records.

    Add a try/catch block around the create, with a second find. If the create fails (due to a primary key constraint), the second find should locate the record created by another thread.