0

Im trying to build a simple web service, right now I only have 3 classes, an entity class, a DAO class and a tester class.

My entity class:

@Entity
@Table(name="sales")
public class Sale implements Serializable{

    @Id
    @Column(name = "idsale_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idsale_id;

    @Column(name = "grand_total", nullable = false)
    private double grand_total;

    public Sale() {
    }

    public Sale(double grand_total) {
        this.grand_total = grand_total;
    }

My Database Operations class

@ApplicationScoped
public class DatabaseOperations {

    @PersistenceContext(unitName = "owlJPA")
    EntityManager em;

    @Transactional
    public String createSale(double grand_total) {
        Sale sale = new Sale(grand_total);
        em.persist(sale);
        em.flush();

        return "Successfully added new entry in DB";
    }
}

REST handling code

@RequestScoped
@Path("/hello-world")
public class HelloResource {

    @Inject
    DatabaseOperations databaseOperations;

    @POST
    @Produces("text/plain")
    @Consumes(MediaType.APPLICATION_JSON)
    public String POSTrecieved(JsonObject jsonRaw) {
        DatabaseOperations databaseOperations = new DatabaseOperations();

        try {
            String tempStr = jsonRaw.getJsonObject("newSale").getString("grand_total");
            double grand_total = Double.parseDouble(tempStr);
            String x = databaseOperations.createSale(grand_total);
            return "SUCESSFULLY ADDED NEW SALE, with grand total of: "+x;
        }
        catch(Exception error){
            return error.toString();
        }
    }

Whenever I try and run a transaction by calling the createSale method, the sale object gets created just fine, but i get a nullPointerException error as my entityManager em is null. But shouldn't my entityManager em already be instantialized as i did @ApplicationScoped?

  • Sorry not being helpful here :( Take a look here https://stackoverflow.com/questions/4132437/entitymanager-injection-nullpointerexception – aran Dec 19 '20 at 05:49
  • Please post the code that uses `DatabaseOperations` – crizzis Dec 19 '20 at 09:07
  • @crizzis i posted it. –  Dec 19 '20 at 19:02
  • Why are you instantiating `DatabaseOperations` yourself? You need to use the injected bean, otherwise the injection of `DatabaseOperations.em` won't work! Just remove the `DatabaseOperations databaseOperations = new DatabaseOperations();` line altogether – crizzis Dec 19 '20 at 20:51
  • @crizzis That fixed it, I am very dumb and still learning about EJB and Java EE, thank youuu so much!. –  Dec 19 '20 at 22:22

0 Answers0