Search using two parameters in JPA

Asked

Viewed 444 times

0

Good night to you all, I am stuck here in a logic, I did the DAO for all the CRUD of my project only that in it will not only have the search for the ID and I am also trying to do some method that researches the request by the ID and also by the registered date. Only at the time of doing the research he’s giving this feedback:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Provided id of the wrong type for class com.exemplo.model.Pedido. Expected: class java.lang.Long, got class java.sql.Date
	at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1135)
	at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1068)
	at com.exemplo.repositorio.MySQLPedidoDAO.pesquisarPorData(MySQLPedidoDAO.java:82)
	at com.exemplo.view.ViewPedidos.btBuscarActionPerformed(ViewPedidos.java:322)
	at com.exemplo.view.ViewPedidos.access$000(ViewPedidos.java:23)
	at com.exemplo.view.ViewPedidos$1.actionPerformed(ViewPedidos.java:106)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
	at java.awt.Component.processMouseEvent(Component.java:6533)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
	at java.awt.Component.processEvent(Component.java:6298)
	at java.awt.Container.processEvent(Container.java:2236)
	at java.awt.Component.dispatchEventImpl(Component.java:4889)
	at java.awt.Container.dispatchEventImpl(Container.java:2294)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
	at java.awt.Container.dispatchEventImpl(Container.java:2280)
	at java.awt.Window.dispatchEventImpl(Window.java:2746)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
	at java.awt.EventQueue.access$500(EventQueue.java:97)
	at java.awt.EventQueue$3.run(EventQueue.java:709)
	at java.awt.EventQueue$3.run(EventQueue.java:703)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
	at java.awt.EventQueue$4.run(EventQueue.java:731)
	at java.awt.EventQueue$4.run(EventQueue.java:729)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.exemplo.model.Pedido. Expected: class java.lang.Long, got class java.sql.Date
	at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:133)
	at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1066)
	at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
	at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2540)
	at org.hibernate.internal.SessionImpl.get(SessionImpl.java:951)
	at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1110)
	... 41 more

My methods were like this: DAO class:

public interface DAO <T, K> {

    public void inserir(T o);
    
    public void alterar(T o);

    public void excluir(T o);

    public T pesquisar(K id);

    public List<T> listar();
    
}

Pedidodion:

public interface PedidoDAO extends DAO <Pedido, Long> {
    
    public Pedido pesquisarPorData(Date dataCadastro);
    
}

Mysqlpedidodao:

public class MySQLPedidoDAO implements PedidoDAO {

    public ConnectionFactory cf = null;

    public MySQLPedidoDAO(ConnectionFactory cf) {
        this.cf = cf;
    }
    
    @Override
    public Pedido pesquisar(Long id) {
        cf.createEm().getTransaction().begin();
        Pedido pedido = cf.createEm().find(Pedido.class, id);
        cf.createEm().getTransaction().commit();
        //erro ao deletar pois o factory já está fechado
        //emf.close();
        return pedido;
    }
    
    @Override
    public Pedido pesquisarPorData(Date dataCadastro) {
        cf.createEm().getTransaction().begin();
        // ERRO ABAIXO!!!!!
        // ERRO ABAIXO!!!!!
        Pedido pedido = cf.createEm().find(Pedido.class, dataCadastro);
        cf.createEm().getTransaction().commit();
        //erro ao deletar pois o factory já está fechado
        //emf.close();
        return pedido;
    }
    
}

Viewpedidos:

public class ViewPedidos extends javax.swing.JInternalFrame {

    private MySQLPedidoDAO mspdao;
    private Pedido ped;
    private boolean editavel;
    
    /* Getters e Setters de editavel e ped  */
    
    private void btPesquisaActionPerformed(java.awt.event.ActionEvent evt) {                                           
        habilitarApenasOSeData();
        limparCampos();
        tfPedido.setEditable(true);
        tfPedido.requestFocus();
        btBuscar.setEnabled(true);
    } 
    
    
    
    private void btBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                         
        ConnectionFactory cf = new ConnectionFactory();
        MySQLPedidoDAO mspdao = new MySQLPedidoDAO(cf);
        Pedido ped = new Pedido();
        
        if(tfPedido.getText().length() == 0  &&  tfDataCad.getText().length() == 0){
             JOptionPane.showMessageDialog(rootPane, "Não é possível pesquisar, Favor preencher os campos", "", JOptionPane.INFORMATION_MESSAGE);
        } else {
             ped = mspdao.pesquisar(Long.parseLong(tfPedido.getText()));
             ped = mspdao.pesquisarPorData(new java.sql.Date(((java.util.Date)tfDataCad.getValue()).getTime()));
             setPed(ped);
             setEditable(true);
             carregarCampos();
             habilitarTextFieldEBotoes();
        }
              
    }   
    
    
} 

I tested commenting on the codes involving the date field and ran smoothly searching for the id, then in that part I invented trying to do a "gambiarra" to get the search by the id and the date and came up with that error above in the stack trace. Would you like to know where I should change? Thank you!

1 answer

0


You’re using the find method to search by date, this method serves to search for an object by the primary key, Exception says you’re passing a Date where you should pass a Long.

Try changing the interface return type and replace the implementation with the method below.

   @Override
    public List<Pedido> pesquisarPorData(Date dataCadastro) {
       String jpql = "select p from Pedido p where dataCadastro = :data";
       List<Pedido> pedidos =  cf.createEm()
                .createQuery(jpql)
                .setParameter("data", dataCadastro)
                .getResultList();

        return pedidos;

    }
  • Hello Matheus!! I didn’t even know who the searchEm(). find(Class.class, id) was only for objects by the primary key now I can be more aware, this method written in the case would be to return a list of vectors or can I return only one object at a time? Tentei executar agora e alterar a chamada de: ped = mspdao.pesquisarPorData(new java.sql.Date(((java.util.Date)tfDataCad.getValue()).getTime‌​())); para: pedidos = (Pedido) mspdao.pesquisarPorData(new java.sql.Date(((java.util.Date)tfDataCad.getValue()).getTime‌​()); but now he is returning Classcastexception

  • What I am in doubt is to do an individual search by searching for a single id only with the two parameters as if it were: "select * from request Where id = ? and dataCadastro = '?'"; and return an object of the requested type. Can be done by createQuery() all in one?

Browser other questions tagged

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