Check if the user informed data already exist in the database before entering

Asked

Viewed 2,319 times

1

I need to check in the database if the information that the user is trying to enter already exists, for example:

In the registration of a company, I cannot allow the same CNPJ for others. I am doing in JSF 2 with JPA2 Hibernate. I made an example of video lesson of Algawors, but there did not show this treatment.

1 answer

1

See if you can do it!

Take a look at the documentation javax/persistence/Query

String cnpjExiste = "123";
Query query = entityManager.createQuery("SELECT sa FROM Empresa AS sa WHERE sa.CNPJ =     ?1", Empresa.class);
query.setParameter(1,  cnpjExiste );
Empresa emp = (Empresa)query.getSingleResult();
if( emp == null ){
  // não existe
 }else{
   // existe
  }


// Ou mais simplificado...

 Empresa empresa = entityManager.find(Empresa.class, 123);
 // empresa == null , não existe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.