So I have this following code:
Query query = session.createQuery("from Weather");
List<WeatherModel> list = query.list();
WeatherModel w = (WeatherModel) list.get(0);
I wan't to get all the items from the table Weather, but I keep getting the following error:(line 23 is where I create the query)
java.lang.NullPointerException
at action.WeatherAction.validate(WeatherAction.java:23)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doBeforeInvocation(ValidationInterceptor.java:251)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)............
What's the problem?
JPQL provides a simple and straightforward way to get all entities from a table. Our Hibernate session's createQuery() method receives a typed query string as the first argument and the entity's type as the second. We execute the query with a call to the getResultList() method which returns the results as a typed List.
Query Object Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects.
The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.
On complex projects I prefer not to hard-code the entity name in a String literal:
Session session = sessionFactory.getCurrentSession();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<WeatherModel> criteriaQuery =
criteriaBuilder.createQuery(WeatherModel.class);
// Your underlying table name might change in the future.
// Let hibernate take care of the names.
Root<WeatherModel> root = criteriaQuery.from(WeatherModel.class);
criteriaQuery.select(root);
Query<WeatherModel> query = session.createQuery(criteriaQuery);
List<WeatherModel> weatherModelList = query.getResultList();
Query query = session.createQuery("from Weather"); //You will get Weayher object
List<WeatherModel> list = query.list(); //You are accessing as list<WeatherModel>
They both are different entities
Query query = session.createQuery("from Weather");
List<Weather> list = query.list();
Weather w = (Weather) list.get(0);
I just had a similar problem, and it appears to have been solved by providing the full path to the object you are trying to query. So, when I made it look like this: session.createQuery("from com.mystuff.something.or.other.MyEntity") it worked.
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