java - How to correctly use entitymanager for creating entity objects? -
good day,
i on first jpa project , have difficulties using , understanding entity manager. have created several classes , assigned them entities via annotations. now, trying create class create entity object via entitymanager. instance, have following class:
@entity @table(name = "product") public class product implements defaultproduct { @id @column(name = "product_name", nullable = false) private string productname; @column(name = "product_price", nullable = false) private double productprice; @column(name = "product_quantity", nullable = false) private int productquantity; @manytoone @joincolumn(name = "product_account", nullable = false) private account parentaccount; public product(string productname, double productprice, int productquantity, account parentaccount) throws illegalargumentexception { if (productname == null || productprice == 0 || productquantity == 0) { throw new illegalargumentexception( "product name/price or quantity have not been specified."); } this.productname = productname; this.productprice = productprice; this.productquantity = productquantity; this.parentaccount = parentaccount; } public string getproductname() { return productname; } public double getprice() { return productprice * productquantity; } public int getquantity() { return productquantity; } public account getaccount() { return parentaccount; } } now, trying create class:
public class createproduct { private static final string persistence_unit_name = "product"; entitymanagerfactory factory = persistence .createentitymanagerfactory(persistence_unit_name); public void createproduct(product product) { entitymanager manager = factory.createentitymanager(); manager.gettransaction().begin(); //code written here manager.gettransaction().commit(); } } can please give me example of code have write down between begin() , commit() lines inside createproduct method; additionally, appreciate if explain how entitymanager works. have read several docs still need clarification.
thanks in advance
account account - new account(); product product = new product("name", 10, 11, account); manager.persist(product); depending when put annotations @column @onetoone , others on fields or getters entitymanager use way gets field values class. uses reflection read annotations , using knows table should looks like. knowing table structure creates query in background ind sends db. analysis of classes done when creating entity manager factory , operation in general time consuming (depends on db structure). understend deaply how works read more reflection. if reflection how simple is.
Comments
Post a Comment