Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type safety: The expression of type List needs unchecked conversion to conform to List<Object[]>

Tags:

java

types

Im getting always a type safety warning when I want to start a Hibernate application. Is there a method to get rid of this without using @SuppressWarnings("unchecked") ?

here is my Code:

Configuration config = new Configuration();
        config.addAnnotatedClass(Employee.class);
        config.configure("hibernate.cfg.xml");

        new SchemaExport(config).create(false, false);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(config.getProperties()).build();
        SessionFactory factory = config.buildSessionFactory(serviceRegistry);

        Session session = factory.getCurrentSession();

        session.beginTransaction();

        Query q = session
                .createQuery("SELECT e.empId,e.empName FROM Employee e");

        @SuppressWarnings("unchecked")
        List<Object[]> list = q.list(); <-- here is the problem!
like image 749
Hakan Kiyar Avatar asked Apr 16 '15 20:04

Hakan Kiyar


3 Answers

Hibernate's Session.list() returns a plain, raw List.

It is perfectly legal Java syntax to cast it to a parameterized collection (List<Object[]> here). But due to the fact that generic type infos are wiped out at runtime, the compiler will emit a warning to tell you it cannot guarantee this cast will actually be valid. So it's just his way to tell you "Hey, you're playing with fire here, I hope you know what you do, because I don't".

In this particular case, you can't do anything to eliminate this warning, but you can take the responsibility of explicitely ignoring it by using the @SuppressWarnings annotation.

like image 69
Olivier Croisier Avatar answered Nov 19 '22 11:11

Olivier Croisier


Another overloaded createQuery() method's accept result type.

createQuery(String queryString, Class<T> resultType)

I don't know which hibernate version added it. Actually it is same result using @SuppressWarnings.

List<Employee> emp = session.createQuery("from Employee", Employee.class).getResultList();

By the way, at Hibernate 5.2 list() is deprecated.

like image 29
Byaku Avatar answered Nov 19 '22 13:11

Byaku


No, there is no way to remove it unless you make q.list() exactly a List<Object[]>

like image 32
nestorishimo10 Avatar answered Nov 19 '22 11:11

nestorishimo10