当我在Servlet中调用onGet方法时,出现NullPointerException。我检查了一下,DAO中的方法已正确实现。我应该在哪里注入EntityManagaer对象?如何注入?在DAO中?还是在Servlet中?我试图用注释来做,但是不起作用。
在方法onGet中,我从ReservationDAO类调用方法getAllReservations(),并且该方法导致Nullpointerexception。我想从数据库中检索数据。这种方法应该从dB返回我想要的所有数据。以及如何解决?
数据库存储两个表,其中包含两个保留对象和两个“人”对象
我的下面的代码:
ReservationServlet类
package servlets;
import DAO.ReservationDAO;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import model.Reservation;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("reservation")
public class ReservationServlet extends HttpServlet {
ReservationDAO reservationDAO = new ReservationDAO();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Reservation> reservationsList = reservationDAO.getAllReservations();
System.out.println("reservationsList size: " + reservationsList.size());
//String json = gson.toJson(reservationsList);
response.getWriter().write(reservationsList.get(0).getPerson().getName());
}
}
ReservationDAO类
package DAO;
import model.Reservation;
import javax.persistence.EntityManager;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.List;
public class ReservationDAO {
@PersistenceUnit(unitName="restapi")
EntityManagerFactory emf = Persistence.createEntityManagerFactory("restapi");
@PersistenceContext(unitName="restapi")
EntityManager em;
@Transactional
public List<Reservation> getAllReservations() {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Reservation> criteriaQuery = builder.createQuery(Reservation.class);
Root<Reservation> employee = criteriaQuery.from(Reservation.class);
criteriaQuery.select(employee);
TypedQuery<Reservation> query = em.createQuery(criteriaQuery);
return query.getResultList();
}
public Reservation getReservationById(EntityManager em, int id) {
Query query = em.createQuery("FROM Reservation WHERE id =" + id);
return (Reservation) query.getSingleResult();
}
public void updateReservation(EntityManager em, int id, Reservation reservation) {
Query query = em.createQuery("UPDATE Reservation SET table_number = :tn, start_time = :st, end_time = :et WHERE id = :id");
query.setParameter("tn", reservation.getTableNumber()).setParameter("st", reservation.getStartTime())
.setParameter("et", reservation.getEndTime()).setParameter("id", reservation.getId()).executeUpdate();
}
public void removeReservation(EntityManager em, int id) {
Query query = em.createQuery("DELETE FROM Reservation WHERE id = :id");
query.setParameter("id", id).executeUpdate();
}
public void createReservation(EntityManager em, Reservation reservation) {
em.persist(reservation);
}
}
预订模型类
package model;
import javax.persistence.*;
@Entity
public class Reservation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "table_number", columnDefinition = "VARCHAR(30) NOT NULL")
private int tableNumber;
@Column(name = "start_time" ,columnDefinition = "VARCHAR(20) NOT NULL")
private String startTime;
@Column(name = "end_time", columnDefinition = "VARCHAR(20) NOT NULL")
private String endTime;
@ManyToOne
private Person person;
public Reservation() {
}
public Reservation(int tableNumber, String startTime, String endTime, Person person) {
this.tableNumber = tableNumber;
this.startTime = startTime;
this.endTime = endTime;
this.person = person;
}
public int getTableNumber() {
return tableNumber;
}
public void setTableNumber(int tableNumber) {
this.tableNumber = tableNumber;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setId(long id) {
this.id = id;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
人员模型课
package model;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
import java.util.Set;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "full_name")
private String name;
@Column(name = "phone_number")
private String phoneNumber;
private String email;
@OneToMany(mappedBy = "person")
private List<Reservation> reservationList;
public Person() {
}
public Person(String name, String phoneNumber, String email, List<Reservation> reservationList) {
this.name = name;
this.phoneNumber = phoneNumber;
this.email = email;
this.reservationList = reservationList;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Reservation> getReservationList() {
return reservationList;
}
public void setReservationList(List<Reservation> reservationList) {
this.reservationList = reservationList;
}
}
应用程序类-我用来通过Hibernate运行应用程序
import DAO.ReservationDAO;
import model.Person;
import model.Reservation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.ArrayList;
import java.util.List;
public class App {
public void populateDb(EntityManager em) {
EntityTransaction transaction = em.getTransaction();
List<Reservation> reservationList = new ArrayList<>();
Person person1 = new Person("John Smith", "458-321-842", "sgfhvdsg@gmail.com", reservationList);
Reservation reservation1 = new Reservation(37, "12.37", "13.45", person1);
reservationList.add(reservation1);
Person person2 = new Person("Gonzalez", "123-456-789", "dsafi@gmail.com", reservationList);
Reservation reservation2 = new Reservation(24, "14.23", "16.22", person2);
reservationList.add(reservation2);
transaction.begin();
em.persist(person1);
em.persist(reservation1);
em.persist(person2);
em.persist(reservation2);
transaction.commit();
}
public static void main(String[] args) {
App app = new App();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("restapi");
EntityManager em = emf.createEntityManager();
app.populateDb(em);
ReservationDAO reservationDAO = new ReservationDAO();
List<Reservation> allReservations = reservationDAO.getAllReservations();
System.out.println("allReservations size: " + allReservations.size());
em.clear();
em.close();
emf.close();
}
}
HTTP ERROR 500
Problem accessing /reservation. Reason:
Server Error
Caused by:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at servlets.ReservationServlet.doGet(ReservationServlet.java:30)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
答案 0 :(得分:0)
在doget方法List<Reservation> reservationsList
中,您得到的为空。你能做什么
if ( reservationsList !=null && !reservationsList.isEmpty())
{
System.out.println("reservationsList size: " + reservationsList.size());
//String json =gson.toJson(reservationsList);
response.getWriter().write(reservationsList.get(0).getPerson().getName()); }
else {
response.getWriter().write("record not found")
}