Java JPA,SpringWeb-如何;查找“;数据库中不存在的记录
我在春天写网络。我对JPA使用Hibernate。我需要在数据库中找到实体,我从用户那个里得到ID 问题是若ID不在数据库中—我得到一个NullPointerException 现在我有:Java JPA,SpringWeb-如何;查找“;数据库中不存在的记录,java,spring,hibernate,jpa,model-view-controller,Java,Spring,Hibernate,Jpa,Model View Controller,我在春天写网络。我对JPA使用Hibernate。我需要在数据库中找到实体,我从用户那个里得到ID 问题是若ID不在数据库中—我得到一个NullPointerException 现在我有: People p; try { p = peopleManager.findById(id); if (p != null) { model.addAttribute("message", "user exist, do any action"); } else { model.a
People p;
try {
p = peopleManager.findById(id);
if (p != null) {
model.addAttribute("message", "user exist, do any action");
} else {
model.addAttribute("message", "user NOT exist");
}
} catch (NullPointerException e) {
model.addAttribute("message", "user NOT exist");
}
但是看起来很糟糕。我怎样才能把它做好
有完整的示例代码:
package com.example.test.entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class People {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name="name")
private String name;
@Column(name="age")
private int age;
}
/* ---------------------------------------------------- */
package com.example.test.dao;
import java.util.List;
import com.example.test.entity.People;
public interface PeopleDao {
public void save(People people);
public void delete(People people);
public void update(People people);
public List<People> findAll();
public People findById(int id);
}
/* ---------------------------------------------------- */
package com.example.test.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.test.entity.People;
@Repository
public class PeopleDaoImpl implements PeopleDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public void save(People people) {
this.sessionFactory.getCurrentSession().save(people);
}
@Override
public void delete(People people) {
this.sessionFactory.getCurrentSession().delete(people);
}
@Override
public void update(People people) {
this.sessionFactory.getCurrentSession().update(people);
}
@Override
public List<People> findAll() {
return this.sessionFactory.getCurrentSession().createQuery("from People ORDER BY age").list();
}
@Override
public People findById(int id) {
return (People) this.sessionFactory.getCurrentSession().get(People.class, id);
}
}
/* ---------------------------------------------------- */
package com.example.test.service;
import java.util.List;
import com.example.test.entity.People;
public interface PeopleManager {
public void save(People people);
public void delete(People people);
public void update(People people);
public List<People> findAll();
public People findById(int id);
}
/* ---------------------------------------------------- */
package com.example.test.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.test.dao.PeopleDao;
import com.example.test.entity.People;
@Service
@Transactional
public class PeopleManagerImpl implements PeopleManager {
@Autowired
private PeopleDao peopleDao;
@Override
public void save(People people) {
peopleDao.save(people);
}
@Override
public void delete(People people) {
peopleDao.delete(people);
}
@Override
public void update(People people) {
peopleDao.update(people);
}
@Override
public List<People> findAll() {
return peopleDao.findAll();
}
@Override
public People findById(int id) {
return peopleDao.findById(id);
}
/* ---------------------------------------------------- */
package com.example.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.test.entity.People;
import com.example.test.service.PeopleManager;
@Controller
public class PeopleController {
@Autowired
private PeopleManager peopleManager;
@RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
public String home(Model model, @PathVariable("id") String id) {
People p;
try {
p = peopleManager.findById(Integer.parseInt(id));
if (p != null) {
model.addAttribute("message", "user exist, do any action");
} else {
model.addAttribute("message", "user NOT exist");
}
} catch (NullPointerException e) {
model.addAttribute("message", "user NOT exist");
}
return "people";
}
}
/* ---------------------------------------------------- */
package com.example.test.entity;
导入javax.persistence.Column;
导入javax.persistence.GeneratedValue;
导入javax.persistence.GenerationType;
导入javax.persistence.Id;
公共阶层人士{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
@列(name=“id”)
私有int-id;
@列(name=“name”)
私有字符串名称;
@列(name=“age”)
私人互联网;
}
/* ---------------------------------------------------- */
包com.example.test.dao;
导入java.util.List;
导入com.example.test.entity.People;
公共接口PeopleDao{
公共空间拯救(人);
公共作废删除(人);
公共无效更新(人);
公共列表findAll();
公共人物findById(int-id);
}
/* ---------------------------------------------------- */
包com.example.test.dao;
导入java.util.List;
导入org.hibernate.SessionFactory;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Repository;
导入com.example.test.entity.People;
@存储库
公共类PeopleDaoImpl实现PeopleDao{
@自动连线
私人会话工厂会话工厂;
@凌驾
公共无效保存(人){
this.sessionFactory.getCurrentSession().save(人员);
}
@凌驾
公共作废删除(人){
this.sessionFactory.getCurrentSession().delete(人);
}
@凌驾
公共无效更新(人){
this.sessionFactory.getCurrentSession().update(人员);
}
@凌驾
公共列表findAll(){
返回此.sessionFactory.getCurrentSession().createQuery(“按年龄排序的人员”).list();
}
@凌驾
公共人物搜索id(int id){
返回(人)this.sessionFactory.getCurrentSession().get(人.class,id);
}
}
/* ---------------------------------------------------- */
包com.example.test.service;
导入java.util.List;
导入com.example.test.entity.People;
公共接口人员管理器{
公共空间拯救(人);
公共作废删除(人);
公共无效更新(人);
公共列表findAll();
公共人物findById(int-id);
}
/* ---------------------------------------------------- */
包com.example.test.service;
导入java.util.List;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Service;
导入org.springframework.transaction.annotation.Transactional;
导入com.example.test.dao.PeopleDao;
导入com.example.test.entity.People;
@服务
@交易的
公共类PeopleManagerImpl实现PeopleManager{
@自动连线
私家人道;
@凌驾
公共无效保存(人){
救人,救人;
}
@凌驾
公共作废删除(人){
peopleDao.delete(人);
}
@凌驾
公共无效更新(人){
更新(人);
}
@凌驾
公共列表findAll(){
return peopleDao.findAll();
}
@凌驾
公共人物搜索id(int id){
返回peopleDao.findById(id);
}
/* ---------------------------------------------------- */
包com.example.test.controller;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Controller;
导入org.springframework.ui.Model;
导入org.springframework.web.bind.annotation.PathVariable;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入com.example.test.entity.People;
导入com.example.test.service.PeopleManager;
@控制器
公共类PeopleController{
@自动连线
私人经理人;
@RequestMapping(value=“/people/{id}”,method=RequestMethod.GET)
公共字符串主(模型模型,@PathVariable(“id”)字符串id){
人p;
试一试{
p=peopleManager.findById(Integer.parseInt(id));
如果(p!=null){
addAttribute(“消息”,“用户存在,执行任何操作”);
}否则{
model.addAttribute(“消息”,“用户不存在”);
}
}捕获(NullPointerException e){
model.addAttribute(“消息”,“用户不存在”);
}
回归“人”;
}
}
/* ---------------------------------------------------- */
重构控制器的null签出。控制器中不应包含任何业务逻辑。正确的位置在服务类中
@Override
@Transactional
public People findById(int id) throws ObjectNotFoundException{
People people = null;
people = peopleDao.findById(id);
if(people == null){
throw new ObjectNotFoundException("Couldn't find a People object with id " + id);
}
return people;
}
我将编写一个自定义异常,该异常扩展在人员对象为null时引发的RuntimeException
这是最佳实践,因为您可以在所有服务层中重用ObjectNotFoundException。然后让所有控制器方法抛出Exception
,并调查控制器的全局错误处理
此外,最好不要将整个服务类注释为
@Transactional
,标记各个方法。这样,如果需要向服务添加其他方法,您可以选择是否希望它们在事务上下文中运行。NPE来自何方?Hibernate javadoc说get()
方法如果找不到它,则返回null,而不使用getEntityManager().find(clazz,id),从不获取NullPointerException