10

所以我有以下代码:

Query query = session.createQuery("from Weather");
        List<WeatherModel> list = query.list();
        WeatherModel w = (WeatherModel) list.get(0);

我不想从表 Weather 中获取所有项目,但我不断收到以下错误:(第 23 行是我创建查询的地方)

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

有什么问题?

4

4 回答 4

11
Query query = session.createQuery("from Weather"); //You will get Weayher object
List<WeatherModel> list = query.list(); //You are accessing  as list<WeatherModel>

他们都是不同的实体

Query query = session.createQuery("from Weather"); 

 List<Weather> list = query.list(); 

Weather w = (Weather) list.get(0);
于 2013-05-04T09:55:51.857 回答
6

在复杂的项目中,我不喜欢在字符串文字中硬编码实体名称:

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();
于 2016-11-23T02:38:56.373 回答
1

我刚刚遇到了类似的问题,它似乎已经通过提供您尝试查询的对象的完整路径来解决。所以,当我让它看起来像这样时: session.createQuery("from com.mystuff.something.or.other.MyEntity") 它起作用了。

于 2014-07-29T17:06:03.523 回答
0

Weather 将是与 WeatherModel 不同的实体。您的列表将包含 Weather 对象,只有当它是 WeatherModel 的子类型时才能强制转换

于 2013-05-04T09:54:04.950 回答