EntityManager em = emf.createEntityManager();
for (int i = 0; i < plan.length; i++) {
if (plan[i].getMonthFunding() < 1 || plan[i].getMonthFunding() > 12)
throw new IllegalArgumentException("Month funding in fundraising plan should be from 1 to 12, found " + plan[i]);
}
Fundraising fundraising = null;
em.getTransaction().begin();
try {
fundraising = em.find(Fundraising.class, year);
if (fundraising == null)
throw new IllegalArgumentException("The fundraising does not exist for this year " + year);
List<FundraisingPlan> previous = new ArrayList<FundraisingPlan>(fundraising.getFundraisingPlans());
//remove the previous instances
for (FundraisingPlan p : previous) {
if (p.getMonthSelected() == monthSelected) {
fundraising.getFundraisingPlans().remove(p);
p.setFundraising(null);
em.remove(p);
}
}
// add the new ones
for (int i = 0; i < plan.length; i++) {
FundraisingPlan p = new FundraisingPlan();
p.setFundraising(fundraising);
p.setMonthSelected(monthSelected);
p.setMonthFunding(plan[i].getMonthFunding());
p.setAmount(plan[i].getAmount());
fundraising.getFundraisingPlans().add(p);
plan[i] = p;
}
//update
fundraising = em.merge(fundraising);
em.getTransaction().commit();