Help with ClassCastException with reflection in hibernate

0

Someone can support me with this exception: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType It happens when I run the following code in a DAO to use hibernate. The problem is in the getEntityClass () function and I am surprised because I used this same code (GenericDAOImpl class) in other projects and it works correctly:

    public class GenericDAOImpl<T, ID extends Serializable> implements GenericDAO<T, ID> {
        public GenericDAOImpl() {...
        public T create() {...
        public void save(T entity){...
        public void update(T entity){...
        public void saveOrUpdate(T entity){...
        public void delete(ID id){...
        public List<T> findAll() {...
        public T get(ID id) throws Exception {
                Session session = sessionFactory.getCurrentSession();
                session.beginTransaction();          
                T entity = (T) session.get(getEntityClass(), id);//Error aqui
                session.getTransaction().commit();
                return entity;
        }
        private Class<T> getEntityClass() {
//En esta linea es donde ocurre el error
                return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    }
    public class Main {
        static GenericDAOImpl<SalesPerson, Long> salespersonDAO=new GenericDAOImpl<SalesPerson, Long>();
        static GenericDAOImpl<Sale, Long> salesDAO=new GenericDAOImpl<Sale, Long>();

        private static void loadSalespeople(){
            SalesPerson sp1=new SalesPerson("Eugenia Martinez",30000f,0.15f);
            SalesPerson sp2=new SalesPerson("Alfredo Perez",33000f,0.20f);
            try {
                salespersonDAO.save(sp1);
                salespersonDAO.save(sp2);
            } catch (Exception e) { 
                e.printStackTrace();
            }
        }
        private static void saveSales(){
            Sale sale1=new Sale(1200.0,0.1f,new Date());
            Sale sale2=new Sale(650.0,0.25f,new Date());
            try {
               //Con esta linea continua el error
                SalesPerson sp1=(SalesPerson)salespersonDAO.get(1L);
                sp1.add(sale1);
                sp1.add(sale2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        private static void deleteSales(){
            try {
                salesDAO.delete(11L);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void main(String[] args) {
            Main.loadSalespeople();
            Main.saveSales();//Aqui empieza el error
            Main.deleteSales();
        }
    }

Updated:

@Entity
public class Sale implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private double total;
    private float discount;
    private Date salesDate;
    @ManyToOne
    @JoinColumn(name="idsalesperson")
    private SalesPerson salesperson;
    //Constructor default
    //Constructor total,discount,discount
    //setters, getters y toString
}

and

@Entity
public class SalesPerson implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String name;
    private float salary;
    private float commission;
    @OneToMany(mappedBy="salesperson",fetch=FetchType.EAGER)
    private Set<Sale> sales=new HashSet<Sale>();
    //Constructor default
    //Constructor name,salary,commission
    //Metodo add(Sale sale)
    //setters, getters y toString
}
    
asked by abrahamhs 24.11.2016 в 20:21
source

1 answer

0

How is your Entity Sales, SalesPerson and others? They have the Extend of the Entity Respository, how is the Entity Repository. If you could post those two classes it would be clearer.

Two possible Solutions after testing.

One if you are using Spring can be problems that there are problems with the libraries because in the Spring Entity Repository it is not of the ParameterizedType type, it is only with extends then you have to do some parsing.

     private Class<T> getEntityClass() {
        Type genericSuperClass = getClass().getGenericSuperclass(); // OBTENEMOS NUESTROS CLASES
        ParameterizedType parametrizedType = null; // INICIAMOS EL TIPO DE PARSEO
        while (parametrizedType == null) { // MIENTRAS ES NULO
            if ((genericSuperClass instanceof ParameterizedType)) { // SI ES EXTENDS
                parametrizedType = (ParameterizedType) genericSuperClass; // CASTEAMOS RECIEN  A ESA CLASE 
            } else {
                genericSuperClass = ((Class<?>) genericSuperClass).getGenericSuperclass();
            }
        }

      entityClass = (Class<T>) parametrizedType.getActualTypeArguments()[0]; 

 return entityClass; // RETORNAMOS RECIEN 
    }

Another possible solution to change your Entity Repository

    
answered by 24.11.2016 в 21:35