[Ljava.lang.Object; can not be cast

4

I have the following problem, I want to make a query to my db, to bring a list of a related class, all worked with hibernate, but when I want to print on the screen it throws me the following error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.historiasclinicas.entidades.Turnos
at com.historiasclinicas.pantallas.PantaListaTurnos.llenarLista(PantaListaTurnos.java:193)
at com.historiasclinicas.pantallas.PantaListaTurnos.access$3(PantaListaTurnos.java:188)
at com.historiasclinicas.pantallas.PantaListaTurnos$2.actionPerformed(PantaListaTurnos.java:127)
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)

The issue is that I have not been able to find accurate information googleando, because it seems to be for several different reasons.

my code is as follows

    public static List<Turnos> ConsultarTurno(String especialista, String fecha) {
    SessionFactory factory;
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (HibernateException he) {
        System.err.println("Ocurrió un error en la inicialización de la SessionFactory: " + he);
        throw new ExceptionInInitializerError(he);
    }

    Session session = factory.openSession();
    List<Turnos> turnos = new ArrayList<Turnos>();
    Transaction transaction = null;

    try {
        Query<Turnos> turno = session.createQuery("select t.fechaTurno, t.estados.estado, t.paciente.id from Turnos as t where t.especialista =:especialista"); 
        turno.setParameter("especialista", especialista);
        turnos = turno.list();
        transaction = session.beginTransaction();
    } catch (HibernateException e) {
        if (transaction != null)
            transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
    return turnos;
}

entity:

    @Entity
@Table(name = "turnos", catalog = "histocons")
public class Turnos implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 8315003380691512767L;
    private Integer id;
    private Estados estados;
    private Paciente paciente;
    private String fechaTurno;
    private String especialista;
    private String horaTurno;

    public Turnos() {
    }

    public Turnos(Estados estados, Paciente paciente, String fechaTurno, String especialista, String horaTurno) {
        this.estados = estados;
        this.paciente = paciente;
        this.fechaTurno = fechaTurno;
        this.especialista = especialista;
        this.horaTurno = horaTurno;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "estado", nullable = false)
    public Estados getEstados() {
        return this.estados;
    }

    public void setEstados(Estados estados) {
        this.estados = estados;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "paciente", nullable = false)
    public Paciente getPaciente() {
        return this.paciente;
    }

    public void setPaciente(Paciente paciente) {
        this.paciente = paciente;
    }

    @Column(name = "fechaTurno", nullable = false, length = 45)
    public String getFechaTurno() {
        return this.fechaTurno;
    }

    public void setFechaTurno(String fechaTurno) {
        this.fechaTurno = fechaTurno;
    }

    @Column(name = "especialista", nullable = false, length = 45)
    public String getEspecialista() {
        return this.especialista;
    }

    public void setEspecialista(String especialista) {
        this.especialista = especialista;
    }

    @Column(name = "horaTurno", nullable = false, length = 45)
    public String getHoraTurno() {
        return this.horaTurno;
    }

    public void setHoraTurno(String horaTurno) {
        this.horaTurno = horaTurno;
    }
}

screen class

package com.historiasclinicas.pantallas;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import com.historiasclinicas.ejecucion.Errores;
import com.historiasclinicas.entidades.Turnos;
import com.historiasclinicas.gestores.GestorTurnos;
import com.historiasclinicas.log.Log;
import com.toedter.calendar.JDateChooser;

public class PantaListaTurnos extends JFrame {

/**
 * 
 */
private static final long serialVersionUID = -4986245537095109601L;
private JPanel contentPane;
private String especialista = PantaLogin.usuario.toString();
private List<Turnos> ListaTurnos = null;
private DateFormat df1;
private JDateChooser dateChooser;
private JButton btnMarcarIngresado;
private JList<Object> List;
private String paciente;
private String fechaTurno;
private Integer Estado;
/**
 * Create the frame.
 */
public PantaListaTurnos() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(PantaListaTurnos.class.getResource("/imagenes/logotipo.png")));
    setTitle("Administrar Turnos Medico");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 890, 444);

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu mnArchivo = new JMenu("Archivo");
    mnArchivo.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/iconos/twentytwo/archive.png")));
    menuBar.add(mnArchivo);

    JMenuItem mntmSalir = new JMenuItem("Salir");
    mntmSalir.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    mntmSalir.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/iconos/twentytwo/close.png")));
    mnArchivo.add(mntmSalir);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GridBagLayout gbl_contentPane = new GridBagLayout();
    gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 32, 0, 0, 0};
    gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
    gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
    contentPane.setLayout(gbl_contentPane);

    JLabel lblTurnos = new JLabel("Turnos");
    lblTurnos.setFont(new Font("Georgia", Font.BOLD, 12));
    lblTurnos.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/iconos/calendar.png")));
    GridBagConstraints gbc_lblTurnos = new GridBagConstraints();
    gbc_lblTurnos.anchor = GridBagConstraints.WEST;
    gbc_lblTurnos.gridwidth = 7;
    gbc_lblTurnos.insets = new Insets(0, 0, 5, 5);
    gbc_lblTurnos.gridx = 1;
    gbc_lblTurnos.gridy = 0;
    contentPane.add(lblTurnos, gbc_lblTurnos);

    JLabel lblIcono = new JLabel("");
    GridBagConstraints gbc_lblIcono = new GridBagConstraints();
    gbc_lblIcono.anchor = GridBagConstraints.EAST;
    gbc_lblIcono.gridwidth = 9;
    gbc_lblIcono.insets = new Insets(0, 0, 5, 5);
    gbc_lblIcono.gridx = 14;
    gbc_lblIcono.gridy = 0;
    contentPane.add(lblIcono, gbc_lblIcono);
    lblIcono.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/logotipo.png")));

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    GridBagConstraints gbc_scrollPane = new GridBagConstraints();
    gbc_scrollPane.gridheight = 5;
    gbc_scrollPane.gridwidth = 20;
    gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
    gbc_scrollPane.fill = GridBagConstraints.BOTH;
    gbc_scrollPane.gridx = 1;
    gbc_scrollPane.gridy = 1;
    contentPane.add(scrollPane, gbc_scrollPane);

    List = new JList<Object>();
    scrollPane.setViewportView(List);

    JButton btnActualizarLista = new JButton("Actualizar Lista");
    btnActualizarLista.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            fechaTurno = df1.format(dateChooser.getDate());
            llenarLista();
        }
    });
    btnActualizarLista.setHorizontalAlignment(SwingConstants.LEFT);
    btnActualizarLista.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/iconos/twentytwo/history.png")));
    GridBagConstraints gbc_btnActualizarLista = new GridBagConstraints();
    gbc_btnActualizarLista.fill = GridBagConstraints.HORIZONTAL;
    gbc_btnActualizarLista.insets = new Insets(0, 0, 5, 5);
    gbc_btnActualizarLista.gridx = 21;
    gbc_btnActualizarLista.gridy = 1;
    contentPane.add(btnActualizarLista, gbc_btnActualizarLista);

    JButton btnIngresarATurno = new JButton("Ingresar a Paciente");
    btnIngresarATurno.setHorizontalAlignment(SwingConstants.LEFT);
    btnIngresarATurno.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/iconos/twentytwo/clipboard.png")));
    GridBagConstraints gbc_btnIngresarATurno = new GridBagConstraints();
    gbc_btnIngresarATurno.fill = GridBagConstraints.HORIZONTAL;
    gbc_btnIngresarATurno.insets = new Insets(0, 0, 5, 5);
    gbc_btnIngresarATurno.gridx = 21;
    gbc_btnIngresarATurno.gridy = 2;
    contentPane.add(btnIngresarATurno, gbc_btnIngresarATurno);

    btnMarcarIngresado = new JButton("Marcar Ingresado");
    btnMarcarIngresado.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                seleccionaTurno();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                try {
                    Log.crearLog(e1.toString());
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                e1.printStackTrace();
            }
        }
    });
    btnMarcarIngresado.setHorizontalAlignment(SwingConstants.LEFT);
    btnMarcarIngresado.setIcon(new ImageIcon(PantaListaTurnos.class.getResource("/imagenes/iconos/twentytwo/check.png")));
    GridBagConstraints gbc_btnMarcarIngresado = new GridBagConstraints();
    gbc_btnMarcarIngresado.fill = GridBagConstraints.HORIZONTAL;
    gbc_btnMarcarIngresado.insets = new Insets(0, 0, 5, 5);
    gbc_btnMarcarIngresado.gridx = 21;
    gbc_btnMarcarIngresado.gridy = 3;
    contentPane.add(btnMarcarIngresado, gbc_btnMarcarIngresado);

    Calendar c2 = new GregorianCalendar();
    df1 = new SimpleDateFormat("dd/MM/yyyy");
    dateChooser = new JDateChooser();
    dateChooser.setCalendar(c2);
    dateChooser.setDateFormatString("dd/MM/yyyy");
    GridBagConstraints gbc_dateChooser = new GridBagConstraints();
    gbc_dateChooser.insets = new Insets(0, 0, 5, 5);
    gbc_dateChooser.fill = GridBagConstraints.BOTH;
    gbc_dateChooser.gridx = 21;
    gbc_dateChooser.gridy = 4;
    contentPane.add(dateChooser, gbc_dateChooser);
}

private void llenarLista() {

    ListaTurnos = GestorTurnos.ConsultarTurno(especialista, fechaTurno);
    DefaultListModel<Object> df = new DefaultListModel<Object>();
    for (int i = 0; i < ListaTurnos.size(); i++) {
        System.out.println((Turnos)ListaTurnos.get(i));
        Turnos tu = (Turnos)ListaTurnos.get(i);
        df.addElement(tu.getPaciente()+" "+tu.getEstados());
    }
    List.setModel(df);
}

public void seleccionaTurno() throws IOException {
    try {
        ListaTurnos.get(List.getSelectedIndex()).getPaciente();
            setPaciente(ListaTurnos.get(List.getSelectedIndex()).getPaciente().getApellido());
        ListaTurnos.get(List.getSelectedIndex()).getEstados().getEstado();                  setEstado(ListaTurnos.get(List.getSelectedIndex()).getEstados().getId());
        Turnos turnos = ListaTurnos.get(List.getSelectedIndex());
        Log.crearLog("Cambio de turno fecha "+fechaTurno+",paciente"+paciente);
        if (Estado<3) 
            GestorTurnos.ActualizaEstado(turnos.getPaciente().getDni());
        else
            Errores.turnoyapasado();
    } catch (Exception e) {
        Log.crearLog(e.getMessage().toString());
    }

}

public String getPaciente() {
    return paciente;
}

public void setPaciente(String string) {
    this.paciente = string;
}

public Integer getEstado() {
    return Estado;
}

public void setEstado(Integer estado) {
    this.Estado = estado;
}

    public String getEspecialista() {
        return especialista;
    }

    public void setEspecialista(String especialista) {
        this.especialista = especialista;
    }

}
    
asked by Pablo Ezequiel Ferreyra 09.10.2016 в 22:19
source

5 answers

0

It is solved by telling hibernate that you must transform the result of each row to the class you want:

.setResultTransformer(Transformers.aliasToBean(TuClaseDTO.class))
    
answered by 09.08.2018 / 21:16
source
2

A small shame of the Java: the Generics only serve for checks at compile time, so if you make mistakes in runtime they will not do you any good.

You do:

Query<Turnos> turno = session.createQuery("select t.fechaTurno, t.estados.estado, t.paciente.id from Turnos as t where t.especialista =:especialista");

And you think that the select will return instances of Turno just because you have parameterized the type, or at least it will inform you that there is a type error. Error. That information is not in execution time, so, what happens is:

  • The compiler makes sure that the result of list() should be treated as List<Turno> (compile error if not). That's fine.

  • The compiler makes sure that by doing a get on that list, the result should be treated as an instance of Turno , correct.

  • When Hibernate returns the result, what it returns is a array list instead of a list of Turno , but at run time there is no check (in fact, there is not even the parameterization information); the runtime expects a List (to dry) and is happy because it has received a List (to dry).

  • When doing the get, you are already assigning an array to a reference to Turno . That's what the JVM checks and throws the error.

And why does it return a list of arrays? Well, because you have made a selection of 3 properties, and not of the entity itself. So it returns, for each entity, an array with those three properties. If you want to recover the entity, simply:

Query<Turnos> turno = session.createQuery("select t from Turnos t where t.especialista =:especialista");

PS:

1) Use the Java naming standard (names of variables and methods use "camelCase" and start with a lowercase letter, it helps a lot to read the code (and how much easier it is to read, easier than someone - yourself included) - find the error).

2) It's usually okay to mark in the code that shows the line where the exception is thrown so that people who read your questions do not have to guess.

    
answered by 10.10.2016 в 16:33
1

The problem:

  

java.lang.ClassCastException: [Ljava.lang.Object; can not be cast   com.historiasclinicas.entidades.Turnos

It is generated in this method:

private void llenarLista() {

    ListaTurnos = GestorTurnos.ConsultarTurno(especialista, fechaTurno);
    DefaultListModel<Object> df = new DefaultListModel<Object>();
    for (int i = 0; i < ListaTurnos.size(); i++) {
        System.out.println((Turnos)ListaTurnos.get(i)); //ERROR!!!
        Turnos tu = (Turnos)ListaTurnos.get(i);
        df.addElement(tu.getPaciente()+" "+tu.getEstados());
    }
    List.setModel(df);
}

Actually ListaTurnos is a list of objects Turnos ( List<Turnos> ), so delete the casting:

 System.out.println(String.valueOf(ListaTurnos.get(i))); 
 Turnos tu = ListaTurnos.get(i);
    
answered by 10.10.2016 в 23:14
0

solved, the problem was the mapping, for some reason I was giving hibernate problems when mapping two tables, but when I removed the mapping of one of them (patient), I solved two problems in one, the data and the show me the last name, which by the query editor returned me as empty

    
answered by 11.10.2016 в 00:26
-1

This seems like an error caused by an unproven or unsafe operation (unchecked or unsafe operation).

A typical example of this error is:

        List<String> lista = new ArrayList<String>();
        List lista2 = lista;
        lista2.add(Integer.valueOf(12));
        String cadena = lista.get(0);

What causes the exception:

  

java.lang.ClassCastException: java.lang.Integer can not be cast   java.lang.String

This is because we have added an Integer to a String list through an untyped list. It is possible that the same thing is happening in your program, although over more separate operations and therefore more difficult to distinguish.

The way to see if this is the case is to check which type returns the call to ListaTurnos.get(i) .

private void llenarLista() {
    ListaTurnos = GestorTurnos.ConsultarTurno(especialista, fechaTurno);
    DefaultListModel<Object> df = new DefaultListModel<Object>();
    for (int i = 0; i < ListaTurnos.size(); i++) {
        System.out.println( ListaTurnos.get(i).getClass().toString(); //Imprime tipo
        Turnos tu = ListaTurnos.get(i);
        df.addElement(tu.getPaciente().getId().toString()+" "+tu.getEstados().getEstado().toString());
    }
    List.setModel(df);
}

If the printed type is not com.historiasclinicas.entidades.Turnos it is a clear indication that the problem is here.

    
answered by 09.10.2016 в 23:32