Я не могу использовать @PersistenceContext с созданным мною новым компонентом, в результате переменная менеджера сущностей всегда будет иметь значение null.
Поэтому я искал в сети решение этой проблемы, но безрезультатно.Вместо этого я попытался использовать EntityManagerFactory, которая отлично возвращает данные, но затем я не могу перенести их в новую переменную того же типа сущности.
Что я заметил, так это то, что содержимое l.get (0) имеет, помимо обычногоПоля объекта Products, некоторые дополнительные поля появляются как _persistence_listener, _persistence_primaryKey и т. Д. ... и затем приведение не будет успешным.
Как я могу снова привести результат к объектам Products, не вызывая исключение "com.jogogestao.entity.Product не может быть приведен к com.jogogestao.entity.Product "?
Tkx!
Код:
public Product getProduct (int ProductId){
private EntityManager em;
private static EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("JogoGestao-ejbPU");
Product p = null;
em = emf.createEntityManager();
Query querysql = em.createQuery("select p from Product p where p.idProduct=" + ProductId);
List<Product> l = querysql.getResultList();
p=l.get(0); //The error occurs here
}
Product.java:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.jogogestao.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author BirdOfPrey
*/
@Entity
@Table(name = "product")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"),
@NamedQuery(name = "Product.findByIdProduct", query = "SELECT p FROM Product p WHERE p.idProduct = :idProduct"),
@NamedQuery(name = "Product.findByProductName", query = "SELECT p FROM Product p WHERE p.productName = :productName"),
@NamedQuery(name = "Product.findByProductBuyPrice", query = "SELECT p FROM Product p WHERE p.productBuyPrice = :productBuyPrice"),
@NamedQuery(name = "Product.findByProductSellPrice", query = "SELECT p FROM Product p WHERE p.productSellPrice = :productSellPrice"),
@NamedQuery(name = "Product.findByProductStoreStockQtd", query = "SELECT p FROM Product p WHERE p.productStoreStockQtd = :productStoreStockQtd"),
@NamedQuery(name = "Product.findByProductShelfSpace", query = "SELECT p FROM Product p WHERE p.productShelfSpace = :productShelfSpace"),
@NamedQuery(name = "Product.findByProductSubCategoryId", query = "SELECT p FROM Product p WHERE p.productSubCategoryId = :productSubCategoryId"),
@NamedQuery(name = "Product.findByProductStoreRefillTime", query = "SELECT p FROM Product p WHERE p.productStoreRefillTime = :productStoreRefillTime"),
@NamedQuery(name = "Product.findByProductStoreCentralQtd", query = "SELECT p FROM Product p WHERE p.productStoreCentralQtd = :productStoreCentralQtd"),
@NamedQuery(name = "Product.findByProductStoreWarehouseQtd", query = "SELECT p FROM Product p WHERE p.productStoreWarehouseQtd = :productStoreWarehouseQtd"),
@NamedQuery(name = "Product.findByProductRange", query = "SELECT p FROM Product p WHERE p.productRange = :productRange"),
@NamedQuery(name = "Product.findByProductWarehouseResponseTime", query = "SELECT p FROM Product p WHERE p.productWarehouseResponseTime = :productWarehouseResponseTime"),
@NamedQuery(name = "Product.findByProductCentralResponseTime", query = "SELECT p FROM Product p WHERE p.productCentralResponseTime = :productCentralResponseTime")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "idProduct")
private Integer idProduct;
@Size(max = 5000)
@Column(name = "ProductName")
private String productName;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Column(name = "ProductBuyPrice")
private BigDecimal productBuyPrice;
@Column(name = "ProductSellPrice")
private BigDecimal productSellPrice;
@Column(name = "ProductStoreStockQtd")
private Integer productStoreStockQtd;
@Column(name = "ProductShelfSpace")
private Integer productShelfSpace;
@Size(max = 100)
@Column(name = "ProductSubCategoryId")
private String productSubCategoryId;
@Column(name = "ProductStoreRefillTime")
@Temporal(TemporalType.TIME)
private Date productStoreRefillTime;
@Column(name = "ProductStoreCentralQtd")
private Integer productStoreCentralQtd;
@Column(name = "ProductStoreWarehouseQtd")
private Integer productStoreWarehouseQtd;
@Column(name = "ProductRange")
private Integer productRange;
@Column(name = "ProductWarehouseResponseTime")
@Temporal(TemporalType.TIME)
private Date productWarehouseResponseTime;
@Column(name = "ProductCentralResponseTime")
@Temporal(TemporalType.TIME)
private Date productCentralResponseTime;
@JoinColumn(name = "ProductCategoryId", referencedColumnName = "idProductCategory")
@ManyToOne
private Productcategory productCategoryId;
public Product() {
}
public Product(Integer idProduct) {
this.idProduct = idProduct;
}
public Integer getIdProduct() {
return idProduct;
}
public void setIdProduct(Integer idProduct) {
this.idProduct = idProduct;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public BigDecimal getProductBuyPrice() {
return productBuyPrice;
}
public void setProductBuyPrice(BigDecimal productBuyPrice) {
this.productBuyPrice = productBuyPrice;
}
public BigDecimal getProductSellPrice() {
return productSellPrice;
}
public void setProductSellPrice(BigDecimal productSellPrice) {
this.productSellPrice = productSellPrice;
}
public Integer getProductStoreStockQtd() {
return productStoreStockQtd;
}
public void setProductStoreStockQtd(Integer productStoreStockQtd) {
this.productStoreStockQtd = productStoreStockQtd;
}
public Integer getProductShelfSpace() {
return productShelfSpace;
}
public void setProductShelfSpace(Integer productShelfSpace) {
this.productShelfSpace = productShelfSpace;
}
public String getProductSubCategoryId() {
return productSubCategoryId;
}
public void setProductSubCategoryId(String productSubCategoryId) {
this.productSubCategoryId = productSubCategoryId;
}
public Date getProductStoreRefillTime() {
return productStoreRefillTime;
}
public void setProductStoreRefillTime(Date productStoreRefillTime) {
this.productStoreRefillTime = productStoreRefillTime;
}
public Integer getProductStoreCentralQtd() {
return productStoreCentralQtd;
}
public void setProductStoreCentralQtd(Integer productStoreCentralQtd) {
this.productStoreCentralQtd = productStoreCentralQtd;
}
public Integer getProductStoreWarehouseQtd() {
return productStoreWarehouseQtd;
}
public void setProductStoreWarehouseQtd(Integer productStoreWarehouseQtd) {
this.productStoreWarehouseQtd = productStoreWarehouseQtd;
}
public Integer getProductRange() {
return productRange;
}
public void setProductRange(Integer productRange) {
this.productRange = productRange;
}
public Date getProductWarehouseResponseTime() {
return productWarehouseResponseTime;
}
public void setProductWarehouseResponseTime(Date productWarehouseResponseTime) {
this.productWarehouseResponseTime = productWarehouseResponseTime;
}
public Date getProductCentralResponseTime() {
return productCentralResponseTime;
}
public void setProductCentralResponseTime(Date productCentralResponseTime) {
this.productCentralResponseTime = productCentralResponseTime;
}
public Productcategory getProductCategoryId() {
return productCategoryId;
}
public void setProductCategoryId(Productcategory productCategoryId) {
this.productCategoryId = productCategoryId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idProduct != null ? idProduct.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Product)) {
return false;
}
Product other = (Product) object;
if ((this.idProduct == null && other.idProduct != null) || (this.idProduct != null && !this.idProduct.equals(other.idProduct))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.jogogestao.entity.Product[ idProduct=" + idProduct + " ]";
}
}
Ошибка:
Caused by: java.lang.ClassCastException: com.jogogestao.entity.Product cannot be cast to com.jogogestao.entity.Product
at com.jogogestao.ejb.DataAccess.getProduct(DataAccess.java:57)
at com.jogogestao.ejb.JogoGestaoSession.addProduct(JogoGestaoSession.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5366)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
at sun.reflect.GeneratedMethodAccessor199.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5338)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5326)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
... 47 more