javahibernatejpadaoentitymanager

How to inject EntityManager to DAO or Servlet using JPA Hibernate


When I calling method onGet in Servlet I got NullPointerException. I checked it and method in DAO is correct implemented. Where should I inject entityManagaer object and how ? In DAO ? Or in Servlet ? I was trying do it with annotations but it doesn't work.

In method onGet I calling method getAllReservations() from ReservationDAO class and that method cause Nullpointerexception. I want retrieve data from my database. This method should return all data from dB what I want get. And how to fix it?

Database store two tables which contains two Reservation objects and two Person objects

My code below:

ReservationServlet class

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 class

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

Reservation model class

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

Person model class

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

App class - what I use to run application by 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)

Solution

  • in doget method List<Reservation> reservationsList you getting is null. what you can do

    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")
    
    }