Hampel Előd
Hampel Előd

Reputation: 435

Select all from a table hibernate

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?

Upvotes: 10

Views: 73147

Answers (4)

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();

Upvotes: 7

user1219387
user1219387

Reputation: 135

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.

Upvotes: 1

PSR
PSR

Reputation: 40318

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);

Upvotes: 11

Ashish Thukral
Ashish Thukral

Reputation: 1485

Weather will be a different entity than WeatherModel. your list will have Weather objects, it can be only cast if it is sub-type of WeatherModel

Upvotes: 0

Related Questions