【问题标题】:Hibernate. Getting all rows return nullPointerException休眠。获取所有行返回 nullPointerException
【发布时间】:2016-05-16 14:58:10
【问题描述】:

我正在尝试从“位置”表中获取所有行。但是我的 DAO 方法总是返回 NullPointerException。我不知道为什么会这样。我已经尝试过 hql、criteria 等,但结果是一样的。

控制器

@Controller
public class HomeController {

@Autowired
private UserService userService;
private FuturePlanService futurePlanService;
private LocationService locationService;

@RequestMapping(value = "/user/{id}/addPlan", method = RequestMethod.GET)
public ModelAndView addFuturePlan(@PathVariable int id){
    ModelAndView modelAndView = new ModelAndView("add_future");
    User user = userService.findById(id);
    FuturePlan futurePlan = new FuturePlan();
    List<Location> locations = locationService.getAll();

    modelAndView.addObject("ownerUser", user);
    modelAndView.addObject("future", futurePlan);
    modelAndView.addObject("locations", locations);

    return modelAndView;
}

位置道

@Repository
public class LocationDaoImpl implements LocationDao {

@Autowired
SessionFactory sessionFactory;

@Override
public Location findLocation(int id) {
    Session session = sessionFactory.openSession();
    Location location = (Location) session.get(Location.class, id);
    session.close();
    return location;
}

@Override
public Location findLocation(String name) {
    Session session = sessionFactory.openSession();
    Criteria cr = session.createCriteria(Location.class);
    cr.add(Restrictions.eq("lName", name));
    cr.setMaxResults(1);
    Location location = (Location) cr.uniqueResult();
    session.close();
    return location;
}

@Override
public List<Location> getAll() {
    Session session = sessionFactory.openSession();
    List<Location> list = session.createQuery("from Location").list();
    session.close();
    return list;
}

}

位置实体

@Entity
public class Location {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int lId;
private String lName;

public Location() {
    super();
}

public Location(int lId, String lName) {
    super();
    this.lId = lId;
    this.lName = lName;
}

public int getlId() {
    return lId;
}

public void setlId(int lId) {
    this.lId = lId;
}

public String getlName() {
    return lName;
}

public void setlName(String lName) {
    this.lName = lName;
}

HTTP 状态 500 - 请求处理失败;嵌套异常是 java.lang.NullPointerException。 在这一行中列出位置 = locationService.getAll();。在控制器中。

如果您需要更多文件,请告诉我。

【问题讨论】:

    标签: java spring hibernate model-view-controller


    【解决方案1】:

    @Autowired 仅适用于直接类成员。添加到locationService

    @Autowired
    private LocationService locationService;
    

    如果 futurePlanService 在您的未来计划中出现,请对它执行相同操作;)

    【讨论】:

    • 谢谢雷默斯!我以为我可以在一个注释下使用多种服务。您的解决方案解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多