jpa - Why is a field of my entity class null? -
i have these 2 entities in 1 many relation:
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; } ...
and
public class product implements serializable { ... @joincolumn(name = "category_id", referencedcolumnname = "id") @manytoone(optional = false) private category categoryid; ...
generated netbeans. problem when method getproductcollection() called controllerservlet collection 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 requested if (userpath.equals("/category")) { // categoryid request string categoryid = request.getquerystring(); if (categoryid != null) { // selected category selectedcategory = categoryfacade.find(short.parseshort(categoryid)); // place selected category in request scope request.setattribute("selectedcategory", selectedcategory); // products selected category categoryproducts = selectedcategory.getproductcollection(); // place category products in request scope request.setattribute("categoryproducts", categoryproducts); }
notice null value of productcollection when other fields has been yet initialized
edit 1: declared categoryfacade in controllerservlet applying @ejb annotation
public class controllerservlet extends httpservlet { @ejb private categoryfacade categoryfacade;
edit 2: here persistence.xml document
<?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>
edit 3: i'm using tomee 7.0.2
the collection may loaded lazily :) when object initialized, internal collection may null. try adding fetch=fetchtype.eager field @onetomany annotation.
Comments
Post a Comment