为什么我的实体类的字段为null?

时间:2017-02-08 11:25:54

标签: jpa

我有这两个实体的一对多关系:

public class Category implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Short id;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
    private Collection<Product> productCollection;

    ...

    @XmlTransient
    public Collection<Product> getProductCollection() {
        return productCollection;
    }

    ...

public class Product implements Serializable {

    ...

    @JoinColumn(name = "category_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Category categoryId;

    ...

使用NetBeans生成。问题是当ControllerServlet调用方法getProductCollection()时,Product of Product为null。

    @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userPath = request.getServletPath();
    Category selectedCategory;
    Collection<Product> categoryProducts;

    // if category page is requested
    if (userPath.equals("/category")) {
        // get categoryId from request
        String categoryId = request.getQueryString();

        if (categoryId != null) {

            // get selected category
            selectedCategory = categoryFacade.find(Short.parseShort(categoryId));

            // place selected category in request scope
            request.setAttribute("selectedCategory", selectedCategory);

            // get all products for selected category
            categoryProducts = selectedCategory.getProductCollection();

            // place category products in request scope
            request.setAttribute("categoryProducts", categoryProducts);
        }

Notice the null value of productCollection when other fields has been yet initialized

编辑1:我在ControllerServlet中使用@EJB注释声明了categoryFacade

public class ControllerServlet extends HttpServlet {

    @EJB
    private CategoryFacade categoryFacade;

编辑2:这是persistence.xml文档

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="AffableBeanPU" transaction-type="JTA">
        <jta-data-source>jdbc/affablebean</jta-data-source>
        <properties/>
    </persistence-unit>
</persistence>

编辑3:我使用的是TomEE 7.0.2

1 个答案:

答案 0 :(得分:-1)

尝试将Collection初始化为空:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
private Collection<Product> productCollection = new HashSet<>();

即使延迟加载关系中没有结果,您也不会有空值。如果有加载的值,它们将被添加到集合中。