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?