使用 EntityManager 和 EntityManagerFactory 将异常转换为实体对象

问题描述 投票:0回答:2

我无法将@PersistenceContext 与我创建的新bean 一起使用,导致实体管理器变量始终为空。

于是我在网上搜索这个问题的解决方案,但没有结果。 相反,我尝试使用 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
}

产品.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
jakarta-ee jpa persistence
2个回答
1
投票

不知何故,你遇到了类加载问题。

List<Product> l = querysql.getResultList();
这里产品使用与您的代码不同的类加载器加载。我想问题就出在这里
private static EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("JogoGestao-ejbPU");

  1. 尝试从代码中获取EntityManagerFactory(不是静态初始化)并查看问题是否解决。

  2. 检查如何定义持久性的使用以及正在使用哪个类加载器。我认为问题在于使用了错误的类加载器来加载

    javax.persistence.*
    类。


0
投票

如果方法

getProduct
位于
servlet
ManagedBean
EJB
中,让容器通过注入来管理PersistenceContext的生命周期:

    @PersistenceContext private EntityManager em;

如果持久性单元在您的

persistence.xml
和容器中正确定义,这就足够了。

为了了解 Enterprise Beans 的用法,请仔细阅读 Java EE 6 教程

© www.soinside.com 2019 - 2024. All rights reserved.