Search field

0

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

But I have a problem about using the name as a search criteria. My search field only returns if the user types EXACTLY as is in the registration. For example, if there is a database with the name "João stack overflow of the silva", the search field must be typed "João stack overflow da silva", including uppercase and lowercase letters. If you miss or miss a letter, the system no longer finds the register. How could I do to make "research less strict"? I wanted to just type "joão" or "stack" or "overflow" or "da silva", the system would already return the registration.

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

User Search.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>

User SearchBean.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;
}
}

Users.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();
}
}

UserFilter.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 removed the part that indicates the package and the imports of the java files. I'm using Eclipse to schedule.

Thanks in advance for any suggestions or opinions.

    
asked by anonymous 08.08.2016 / 00:00

1 answer

1

Dude, there are ways you can do something like that. But if you want the simplest way to do it and do not want to create a google in life, you can use the keyword LIKE in your sql.

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

What is happening in this query is this: you type "john" there inside <busca_desejada> it will return only the records with john. When we add the % it will return everything that is BEFORE or AFTER the desired search. It is as if you were talking like this to the data bank: OR, I RETURN TO ALL THAT HAS THE WORD 'JOHN' IN THE MIDDLE.

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

That's the simplest way I know it. And also to remove this case sensitive business, you have to do:

  • Remove this in the database settings

OR

  • Convert the entire string from both the database and the query to a lowercase / uppercase. (which I recommend)

These are the ways I know you can do this in a not-so-complicated way.

    
08.08.2016 / 00:50