简体   繁体   中英

Java EE managed Container Collection operation not Propagating to DB

I will confessed that I have got really confused lately and I need to take a step back and start the basics again for Java EE.

After reading some materials I got the believing that I can do some operations on my entities or collections and this will be translated by the Container or JPA to some sql. I tried this and it worked as I expected

  public List<Manufacturer> addProductByContainerManaged(Integer manufacId, Product prod){
    Manufacturer manu = this.manufacturerDao.find(manufacId);
    manu.getProductList().add(prod);
    prod.setManufacturerId(manu);
    return this.manufacturerDao.findAll();
}

But this operation didnt add any item in the DB, so I guess I am missing something.

  public List<Manufacturer> addManufacturer(Manufacturer manufac){  
    List<Manufacturer> ret = this.manufacturerDao.findAll();
    ret.add(manufac);
   return ret;
}

The second snippet just adds the Manufacturer manufac object to the java List (see: http://docs.oracle.com/javase/7/docs/api/java/util/List.html ). Then your method returns this list. Calling add(...) on the List element does just that, adds an element to the list.

If you want to add it to the DB, you obviously have to call the add(...) method implemented by you (or whoever) on the ManufacturerDAO in order to save it in the DB (like in the first snippet).

If you want the second snippet to work, then you have to do something like:

public List<Manufacturer> addManufacturer(Manufacturer manufac){  
    this.manufacturerDao.save(manufac); //I am not sure about your api. It could be something like this.
    List<Manufacturer> ret = this.manufacturerDao.findAll();
    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM