开发者

To catch the reason of the unique constraint on JPA

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");
开发者_JS百科        } 
    // 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.


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...


Try this:

catch(javax.validation.ConstraintViolationException exception) {
    Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜