Do not re-enter an existing login user

Asked

Viewed 53 times

1

I have a JPA problem with Java.

I built a login system, using a self-generated ID, but every time I run the program it creates another user in the database, with a different id but same credentials.

How do I so that if there is already this user login, it does not create another equal?

Method that starts along with the application:

public void startApp() {

    service = new Service<List<Usuario>>() {
        @Override
        protected Task<List<Usuario>> createTask() {
            return new Task<List<Usuario>>() {
                @Override
                protected List<Usuario> call() throws Exception {

                   Usuario user = new Usuario();
                    user.setNome("Usuario");
                    user.setLogin("user");
                    user.setSenha("123");

                    UsuarioDAO usuarioDAO = new UsuarioDAO();
                    usuarioDAO.inserir(user);
                    return usuarioDAO.obterLista();
                }
            };
        }
    };

Insert Method from JPA

public boolean inserir(Usuario usuario) {
    try {
        entidadeGerenciamento.getTransaction().begin();              
        entidadeGerenciamento.persist(usuario);
        entidadeGerenciamento.getTransaction().commit(); 
        return true;

1 answer

1


You could check if the user, based on the login, already exists before performing the insertion.

public boolean usuarioExistente(Usuario usuario) {
    try {
        Usuario usuario = (Usuario) entidadeGerenciamento.createQuery("SELECT u FROM Usuario u WHERE u.login LIKE :login").setParameter("login", "%" + usuario.getLogin() + "%").getSingleResult();
        return true; // Se encontrou registro, então OK!
    } catch (NoResultException ex) {
       return false; // Caso não exista registro
    }
}

And your code to enter could do something:

public boolean inserir(Usuario usuario) {
  if (this.usuarioExistente(usuario)) { 
    return false;
  }
  try {
     entidadeGerenciamento.getTransaction().begin();              
     entidadeGerenciamento.persist(usuario);
     entidadeGerenciamento.getTransaction().commit(); 
     return true;
  } // continuação do código

Browser other questions tagged

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