JBoss Community

Concurrence management

created by Alessandro Laurucci in EJB3 - View the full discussion

Hi to all,

I'm developing my first EJB3 application with eclipse. I don't know i manage the insert into a database in case of duplicate key.

 

 

I use this code:

 

Table KGTWANAUSER01:

-user (key)

-password

 

 

Entity bean:

import java.io.Serializable;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

 

@Entity @Table(name="KGTWANAUSER01")

public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id @Column(name="USER") private String USER;

@Column(name="PASSWORD") private String PASSWORD;

 

 

public User(String us, String pswd)

{ this.user=us; this.password=pswd; }

 

 

public String getUSER()

{ return USER; }

 

 

public String getPASSWORD()

{ return PASSWORD; }

 

 

public void setUSER(String uSER)

{ USER = uSER; }

 

 

public void setPASSWORD(String pASSWORD)

{ PASSWORD = pASSWORD; }

}

 

 

#

Stateless Session Bean (register method):

....

 

public String register(String user, String password)

   { 

      User us = new User (user, password)     

      List existing = em.createQuery(

         "select username from User where username = #{user.username}")

         .getResultList();

        

      if (existing.size()==0)

      {

         em.persist(us);

          return "OK";

#

      }      

 

      else

      {

         return "NO;"

      }

   }

....

 

 

My problem is this:

 

I have two client A e B that want to create their new user, both with the username "ale":

 

A call register method, execute the select, no other user "ale" are register so existing.size=0;

B call the same method, and also in this case no other user "ale" are register so existing.size=0;

A make em.persist(us) adn the transaction is OK

B try to make the insert with the persist, but the user now exist, so the application crashs and Jboss show me a list of errors caused by the duplicate key...

 

Ho i can solve this problem?

Thanks to All

 

Alessandro

Reply to this message by going to Community

Start a new discussion in EJB3 at Community