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!
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.
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.
No, there is no way to remove it unless you make q.list() exactly a List<Object[]>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With