To catch the reason for the unique restriction on JPA

I am trying to learn JPA and I have a problem that I am stuck with from two days.

I have a table called "User" that includes an identifier, email address, password, username and status.

Do you think the columns of letters and username are unique.

I also have a class called User, something like this:

@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; 

The rest of this class is getters and seters.

I am trying to insert a value 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 the problem with the username restriction or the unique email restriction? While you can check the start and end block of Attention, I'm sure you will get my point :)

Thanks in advance.

+4
source share
2 answers

You should not use automatically generated schemas in the production process, so why not just give the name contraint in your schema. Then, when an exception is thrown, you will get the name of the failed constraint.

 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 look in the database before inserting them to see if they are there .. so you will most likely not get an exception ...

+2
source

Try the following:

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

All Articles