我试图构建一个简单的web服务,现在我只有3个类,一个实体类,一个dao类和一个tester类。
我的实体类:
@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;
}
我的数据库操作类
@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";
}
}
休息处理代码
@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();
}
}
每当我尝试通过调用createsale方法来运行事务时,sale对象都会被很好地创建,但是当entitymanager em为null时,我会得到一个nullpointerexception错误。但是我的entitymanager em不应该像@applicationscoped那样被示例化吗?
暂无答案!
目前还没有任何答案,快来回答吧!