Field of research

Asked

Viewed 283 times

0

Hello, everyone. I’m putting together a program that has the user registration function. The program is done in Java, xhtml and I am using Primefaces to generate the visual components. In this program there is also a search screen to search registered users using the name as criterion.

But I have a problem with using the name as a research criterion. My search field only returns if the user type EXACTLY as it is in the registration. For example, if there is a register in the database with the name "João stack overflow da silva", in the search field you have to type "João stack overflow da silva", including upper and lower case. If a letter is missing or misspelled, the system no longer finds the register. How could I make the search "less rigid"? I just wanted to type "joão" or "stack" or "overflow" or "da silva", the system already returned the registration.

I am sending the files that make up the screen. It is a xhtml file and three Java files.

Searcher.xhtml.

<ui:define name="titulo">Pesquisar Usuarios</ui:define>

<ui:define name="corpo">
    <h:form id="frmPesquisa">
    <p:messages showDetail="false" showSummary="true" autoUpdate="true" />

    <h1>Pesquisa de usuários</h1>

    <p:toolbar style="margin-top: 20px">
        <p:toolbarGroup>
            <p:commandButton value="Pesquisar" action="#{pesquisaUsuarioBean.pesquisar}" update="@form" />
            <p:selectOneRadio id="id" value="#{pesquisaUsuarioBean.filtro.status}" >
                <f:selectItem itemLabel="Ativo" itemValue="Ativo" />
                <f:selectItem itemLabel="Inativo" itemValue="Inativo" />
            </p:selectOneRadio>
        </p:toolbarGroup>
        <p:toolbarGroup align ="right">
            <p:button value="Novo" outcome="/usuarios/CadastroUsuario"/>
        </p:toolbarGroup>
    </p:toolbar>

    <p:panelGrid columns="2" id="painel" style="width: 100%; margin-top: 20px" columnClasses="rotulo, campo">
        <p:outputLabel value="Nome" for="nome"/>
        <p:inputText id="nome" size="60" maxlength="80"
        value="#{pesquisaUsuarioBean.filtro.nome}"/>
    </p:panelGrid>

    <p:dataTable id="usuariosTable"
            value="#{pesquisaUsuarioBean.usuariosFiltrados}" var="usuario"
            style="margin-top: 20px" emptyMessage="Nenhum usuario encontrado."
            rows="20" paginator="true" paginatorAlwaysVisible="false"
            paginatorPosition="bottom">

    <p:column headerText="Id" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.id}" />
    </p:column>

    <p:column headerText="Nome" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.nome}" />
    </p:column>

    <p:column headerText="RG" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.rg}" />
    </p:column>

    <p:column headerText="CPF" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.cpf}" />
    </p:column>

    <p:column headerText="Email" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.email}" />
    </p:column>

    <p:column headerText="Telefone" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.telefone}" />
    </p:column>

    <p:column headerText="Endereço" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.endereco}" />
    </p:column>

    <p:column headerText="Estado" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.estado}" />
    </p:column>

    <p:column headerText="CEP" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.cep}" />
    </p:column>

    <p:column headerText="Status" style="text-align: center; width: 100px">
            <h:outputText value="#{usuario.status}" />
    </p:column>

    <p:column headerText="Operações" style="width: 100px; text-align: center">
    <c:set var ="status" scope = "session"/>
            <p:button outcome = "/usuarios/CadastroUsuario" icon="ui-icon-pencil" title="Editar" disabled ="#{pesquisaUsuarioBean.inativo}">
                <f:param name="usuario" value="#{usuario.id}" />
            </p:button>
            <p:commandButton icon="ui-icon-bloquear" title="Alterar status do cadastro" oncomplete="PF('confirmacaoExclusao').show()" process="@this" update="frmPesquisa:confirmacaoExclusaoDialog">
                <f:setPropertyActionListener value="#{usuario}" target="#{pesquisaUsuarioBean.usuarioSelecionado}"/>    
            </p:commandButton>
    </p:column>


    </p:dataTable>

        <p:confirmDialog header="Alterar status do cadastro"
            message="Tem certeza que deseja alterar o status do cadastro do usuário #{pesquisaUsuarioBean.usuarioSelecionado.nome}?"
            widgetVar="confirmacaoExclusao" id="confirmacaoExclusaoDialog">
            <p:button value="Não"
                onclick="PF('confirmacaoExclusao').hide(); return false;" />
            <p:commandButton value="Sim"
                oncomplete="PF('confirmacaoExclusao').hide();" action="#{pesquisaUsuarioBean.excluir}" process="@this" update="frmPesquisa:usuariosTable"/>
        </p:confirmDialog>
</h:form>
</ui:define>

Search user.java.

@Named
@ViewScoped
public class PesquisaUsuarioBean implements Serializable{

private static final long serialVersionUID = 1L;

@Inject
private UsuariosRep usuarios;

private UsuarioFilter filtro;

private List<Usuario> usuariosFiltrados;

private Usuario usuarioSelecionado;

@Inject
private CadastroUsuarioService cadastroUsuarioService;

public PesquisaUsuarioBean() {
    filtro = new UsuarioFilter();
}

public boolean isInativo() {
    boolean inativo = false;
    for (int x = 0;x < this.usuariosFiltrados.size(); x++)
    {
        String ContasInativas = this.usuariosFiltrados.get(x).getStatus();
        if ( ContasInativas.equals("Inativo"))
        {
            inativo = true;
        }
    }
    return inativo;
}

public void excluir() {
    FacesContext context = FacesContext.getCurrentInstance();
    if (this.usuarioSelecionado.getStatus().equals("Ativo"))
    {
        this.usuarioSelecionado.setStatus("Inativo");
    }
    else
    {
        this.usuarioSelecionado.setStatus("Ativo");
    }
    try {
        this.cadastroUsuarioService.salvar(this.usuarioSelecionado);
        context.addMessage(null, new FacesMessage("O status do cadastro do usuário " + usuarioSelecionado.getNome() + " com o CPF : " + usuarioSelecionado.getCpf() + " foi alterado com sucesso."));
        this.pesquisar();
    } catch (NegocioException e) {
        FacesMessage mensagem = new FacesMessage(e.getMessage());
        mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
        context.addMessage(null, mensagem);
    }
}

public void pesquisar() {
    usuariosFiltrados = usuarios.filtrados(filtro);
}

public List<Usuario> getUsuariosFiltrados() {
    return usuariosFiltrados;
}

public UsuariosRep getUsuarios() {
    return usuarios;
}

public UsuarioFilter getFiltro() {
    return filtro;
}

public Usuario getUsuarioSelecionado() {
    return usuarioSelecionado;
}

public void setUsuarioSelecionado(Usuario usuarioSelecionado) {
    this.usuarioSelecionado = usuarioSelecionado;
}
}

Usuariosrep.java

public class UsuariosRep implements Serializable {

private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;

public Usuario guardar(Usuario usuario) {
    EntityTransaction trx = manager.getTransaction();

    trx.begin();

    usuario = manager.merge(usuario);

    trx.commit();

    return usuario;
}

public Usuario porNome(String nome) 
{
    return manager.find(Usuario.class, nome);
}

public Usuario porId(Long id)
{
    return manager.find(Usuario.class, id);
}

public List<Usuario> listaDeUsu() 
{
    return manager.createQuery("from Usuario", Usuario.class).getResultList();
}

public List<Usuario> raizes()
{
    return  manager.createQuery("from Usuario",Usuario.class).getResultList(); 
}

@SuppressWarnings("unchecked")
public List<Usuario> filtrados(UsuarioFilter filtro) {

    Session session = manager.unwrap(Session.class);

    Criteria criteria = session.createCriteria(Usuario.class);

    if (filtro.getNome() != null) 
    {
        criteria.add(Restrictions.eq("nome", filtro.getNome()));
    }

    if (filtro.getStatus() != null)
    {
        criteria.add(Restrictions.eq("status", filtro.getStatus()));
    }

    // orderBy do SQL
    return criteria.addOrder(Order.asc("id")).list();
}

public void remover(Usuario usuario) {
    this.manager.remove(usuario);
    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    manager.flush();
    trx.commit();
}
}

Usuariofilter.java

public class UsuarioFilter implements Serializable {
private static final long serialVersionUID = 1L;

private String nome;
private String status = "Ativo";

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}
}

To shorten the codes, I have removed the part that indicates the package and the Imports from the java files. I am using Eclipse to program.

Thanks in advance for any suggestions or opinions.

1 answer

1

Man, it’s like, there’s a lot of ways you can do something like this. But if you want the simplest way to do it and don’t want to create a google of life, you can use keyword LIKE in your sql.

select nome from usuarios where nome like %<busca_desejada>%;

What is happening in this query is the following: you type "john" there inside the <busca_desejada> it will return only the records with John. When we add the % it will return all that is BEFORE or AFTER the desired search. It’s like you speak to the database like this: OR, GIVE ME BACK EVERYTHING THAT HAS THE WORD 'JOHN' IN BETWEEN.

The problem of doing the above is that it will return everything it finds within the bank that matches the desired search. In case, what is in <busca_desejada>. To return only one record of this query you can add one LIMIT 1 at the end of the consultation.

This is the simplest way I know how to do it. And also to get this business out of the case sensitive, you have to do:

  • Remove this in the database settings

OR

  • Convert the entire string of both the databank and query into minuscule/uppercase. (what I recommend)

These are the ways I know you can do it in a way that’s not so complicated.

Browser other questions tagged

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