Verify that the data entered by the user already exists in the database before inserting

1

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

In the registration of a company, I can not allow the same CNPJ for others. I'm doing in JSF 2 with JPA2 Hibernate. I did an example video lesson from Algawors, but there was no such treatment.

    
asked by anonymous 20.04.2015 / 15:53

1 answer

1

See if you can do this!

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
    
20.04.2015 / 16:17