views:

80

answers:

2

Hello everyone. I am trying to learn JPA and I have a problem that I stucked in since 2 days.

I have a table named "User" includes id,email,password,username and status.

As you guess email and username columns are unique.

I also have a Class called User something like that :

@Entity
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = {"username", "email"}))
public class User {    
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    @Column(name="email", nullable=false)
    private String email;
    @Column(name="password", nullable=false)
    private String password;
    @Column(name="username", nullable=false)
    private String username;
    @Column(name="status", nullable=false)
    private String status; 

Rest of this class is getters and setters.

I am trying to insert a value by using JPA with Hibernate.

    try {
            em = jpaResourceBean.getEMF().createEntityManager();
            em.getTransaction().begin();
            user.setStatus(UserStatus.PENDING.toString());
            em.persist(user);
            em.getTransaction().commit();
            logger.info("User " + user.getUsername() + " has been registered");
    // Attention starts
        } catch (XXXXXX) { 
    if (XXXXX.getYYY().equals("ZZZZZ")) logger.info("User name is already exist");
    if (XXXXX.getMMM().equals("LLLLL")) logger.info("Email is already exist");
        } 
    // Attention end

All I want to know : How can I understand is the problem with the username constraint or the email unique constraint? While you can check my Attention start and end block, I am sure that you get my point : )

Thanks in advance.

A: 

Try this:

catch(javax.validation.ConstraintViolationException exception) {
    Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
...
}
tob
Sadly, in case of a unique constraint violation, you'll get a `PersistenceException`, Bean Validation won't be here.
Pascal Thivent
+1  A: 

You should not use auto-generated schemas in production, so why not simply set the contraint name in your schema. Then when the exception is generated, you will get the failing constraint name.

create table users (
      user varchar2(20) not null,
      email varchar2(20) not null,

      constraint user_uq unique(user),
      constraint email_uq unique(email)
)

You might want to have a look in the database before you insert to see if they are already there.. that way you most likely wont get an exception anyway...

time4tea
Hi, I would like to say that is what I want. It is no matter who gave the constraint name. It may be mine or it may be auto generated. The point is catchin' its name from the code. And actually I do not want to look in the database before I insert. Because I don't want to go to the database twice. That's why I want to get constraint name from java Exception.
Brad Revolver