public void updateCompany(CompanyDTO dto) throws Exception { Company company = getCompany(dto.id); validate(dto); List<String> beneficiaryIds = company .getBeneficiaries() .stream() .map(beneficiary -> beneficiary.getId().toString()) .collect(Collectors.toList()); for (BeneficiaryDTO beneDTO : dto.beneficiaries) { Beneficiary bene = new Beneficiary(beneDTO.name, company); Integer id = beneDTO.id; if (id != null) { bene.setId(id); String idString = id.toString(); if (!beneDao.idExists(idString)) { throw new RequestException("beneficiary with id %s does not exist", id); } beneDao.update(bene); beneficiaryIds.remove(idString); } else { beneDao.create(bene); } } if (beneficiaryIds.size() > 0) { beneDao.deleteIds(beneficiaryIds); } company = JsonUtil.fromJson(dto.toJson(), Company.class); dao.update(company); }
public void createCompany(CompanyDTO dto) throws Exception { validate(dto); Boolean exists = dao.idExists(dto.id); if (exists) { throw new RequestException("Company with id %s already exists", dto.id); } Company company = JsonUtil.fromJson(dto.toJson(), Company.class); company.setCreatedAt(); dao.create(company); for (BeneficiaryDTO beneDTO : dto.beneficiaries) { beneDao.create(new Beneficiary(beneDTO.name, company)); } }