List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java
/** * Save the flexible elements of imported organizational unit model * //w ww. j ava2 s . c o m * @param orgUnitModel * the imported organizational unit model * @param em * the entity manager */ private void saveOrgUnitFlexibleElement(OrgUnitModel orgUnitModel, EntityManager em) { // OrgUnitModel --> Banner --> Layout --> Groups --> Constraints if (orgUnitModel.getBanner() != null && orgUnitModel.getBanner().getLayout() != null) { List<LayoutGroup> bannerLayoutGroups = orgUnitModel.getBanner().getLayout().getGroups(); if (bannerLayoutGroups != null) { for (LayoutGroup layoutGroup : bannerLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveOrgUnitModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveOrgUnitModelCategoryElement(element, em); } } type.setElements(typeElements); em.merge(type); } } //Set the saved CategoryType to QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } //Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } // OrgUnitModel --> Detail --> Layout --> Groups --> Constraints if (orgUnitModel.getDetails() != null && orgUnitModel.getDetails().getLayout() != null) { List<LayoutGroup> detailLayoutGroups = orgUnitModel.getDetails().getLayout().getGroups(); if (detailLayoutGroups != null) { for (LayoutGroup layoutGroup : detailLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveOrgUnitModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveOrgUnitModelCategoryElement(element, em); } } type.setElements(typeElements); em.merge(type); } } //Set the saved CategoryType to QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } //Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } }
From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java
/** * Guarda las nuevas firmas de la persona, integrando las relaciones PersonaFirma de acuerdo a si las * firmas existen o no en la base de datos. * NO borra las firmas que ahora no estn y antes si estaban. * NO deben existir firmas repetidas en la lista que se va a guardar. * @param em EntityManager a usar, debe estar ya dentro de un EntityManager.begin(); * @param persona Persona del que se almacenar las firmas, NO debe tener firmas repetidas *//*from w w w . ja va 2s .c om*/ private void guardarPersonaFirma(EntityManager em, Persona persona) { for (PersonaFirma perFirma : persona.getPersonaFirmasCollection()) { //Firma firmaExistente = findFirma(em, perFirma.getFirma().getNombre()); PersonaFirma perFirmaExistente = findPersonaFirma(persona.getId(), perFirma.getFirma().getNombre()); Firma firmaExistente = findFirma(em, perFirma.getFirma().getNombre()); if (firmaExistente != null) { if (perFirmaExistente != null) { //significa que ya existe la firma en la db y tambin ya existe una relacin entre la firma y la persona que se modifica // por lo tanto no hay que realizar modificacin alguna //En caso de PersonaFirma tenga campos adicionales, aqu se los debera editar, mientras tanto sigue comentado el cdigo //perFirma.setId(perFirmaExistente.getId()); //em.merge(perfirma); } else { //si la firma existe pero no hay relacin entre la firma y la persona, entonces significa que la persona que se est editando // va a tener una firma que es usado por varias personas, por lo tanto hay que agrega una nueva PersonaFirma indicando // la relacin entre la persona que se est editanto y la firma que ya existe perFirma.setId(null); perFirma.setPersona(persona); perFirma.setFirma(firmaExistente); em.persist(perFirma); } } else { //si no existe la firma, se debe crear tanto la PersonaFirma como la Firma, independientemente de los ids que tengan perFirma.getFirma().setId(null); perFirma.setPersona(persona); em.persist(perFirma.getFirma()); perFirma.setId(null); em.persist(perFirma); } } }
From source file:uk.ac.horizon.ug.locationbasedgame.client.InformLocation.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w w w . ja v a 2s . c o m // expects: { "conversationId":"...", "clientId":"...", "latitudeE6":123, "longitudeE6":123, // "radiusMetres":1.0, "altitudeMetres":1.0} JSONObject jreq = parseObject(req); String conversationId = jreq.getString(CONVERSATION_ID); Key gameKey = null; EntityManager em = EMF.get().createEntityManager(); try { Query q = em.createQuery("SELECT x FROM " + GameClient.class.getSimpleName() + " x WHERE x.currentConversationId = :currentConversationId"); q.setParameter("currentConversationId", conversationId); q.setMaxResults(2); List results = q.getResultList(); if (results.size() > 1) logger.log(Level.WARNING, "More than one GameClient with conversationId " + conversationId); if (results.size() == 0) throw new RequestException(HttpServletResponse.SC_BAD_REQUEST, "conversationId unknonwn: " + conversationId); GameClient gc = (GameClient) results.get(0); // sanity check String clientId = jreq.getString(CLIENT_ID); if (!gc.getClientId().equals(clientId)) throw new RequestException(HttpServletResponse.SC_BAD_REQUEST, "conversationId -> GameClient " + gc + " with different clientId cf. " + clientId); ClientLocation cloc = new ClientLocation(); cloc.setCreatedTime(System.currentTimeMillis()); cloc.setKey(ClientLocation.makeKey(gc, cloc.getCreatedTime())); cloc.setAltitudeMetres((float) jreq.getDouble(ALTITUDE_METRES)); cloc.setCurrent(true); cloc.setGameClientKey(gc.getKey()); gameKey = gc.getGameKey(); cloc.setGameKey(gameKey); cloc.setLatitudeE6(jreq.getInt(LATITUDE_E6)); cloc.setLongitudeE6(jreq.getInt(LONGITUDE_E6)); cloc.setRadiusMetres((float) jreq.getDouble(RADIUS_METRES)); em.persist(cloc); logger.log(Level.FINE, "added ClientLocation: " + cloc); // non-current any old one... q = em.createQuery("SELECT x FROM " + ClientLocation.class.getSimpleName() + " x WHERE x.gameClientKey= :gameClientKey AND x.current= TRUE AND x.createdTime < :createdTime"); q.setParameter("gameClientKey", gc.getKey()); q.setParameter("createdTime", cloc.getCreatedTime()); List<ClientLocation> clocs = (List<ClientLocation>) q.getResultList(); for (ClientLocation cl : clocs) { cl.setCurrent(false); logger.log(Level.FINER, "Marked not current ClientLocation " + cl); } } finally { em.close(); } returnLocations(resp, gameKey); } catch (RequestException re) { resp.sendError(re.getErrorCode(), re.getMessage()); } catch (JSONException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString()); } }
From source file:com.jada.admin.contactus.ContactUsMaintAction.java
private void saveLanguage(ContactUs contactUs, ContactUsMaintActionForm form, AdminBean adminBean) throws Exception { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); ContactUsLanguage contactUsLanguage = null; User user = adminBean.getUser();/*w w w . j a v a2 s . c o m*/ Long siteProfileClassId = form.getSiteProfileClassId(); boolean found = false; Iterator<?> iterator = contactUs.getContactUsLanguages().iterator(); while (iterator.hasNext()) { contactUsLanguage = (ContactUsLanguage) iterator.next(); if (contactUsLanguage.getSiteProfileClass().getSiteProfileClassId().equals(siteProfileClassId)) { found = true; break; } } if (!found) { contactUsLanguage = new ContactUsLanguage(); contactUsLanguage.setRecCreateBy(user.getUserId()); contactUsLanguage.setRecCreateDatetime(new Date(System.currentTimeMillis())); SiteProfileClass siteProfileClass = em.find(SiteProfileClass.class, siteProfileClassId); contactUsLanguage.setSiteProfileClass(siteProfileClass); contactUs.getContactUsLanguages().add(contactUsLanguage); } if (form.isContactUsNameLangFlag()) { contactUsLanguage.setContactUsName(form.getContactUsNameLang()); } else { contactUsLanguage.setContactUsName(null); } if (form.isContactUsDescLangFlag()) { contactUsLanguage.setContactUsDesc(form.getContactUsDescLang()); } else { contactUsLanguage.setContactUsDesc(null); } contactUsLanguage.setRecUpdateBy(user.getUserId()); contactUsLanguage.setRecUpdateDatetime(new Date(System.currentTimeMillis())); em.persist(contactUsLanguage); }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
public ServiceDetail saveService(SaveService body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {/*from ww w . ja v a 2 s.c om*/ tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveService(em, body, null); ServiceDetail result = new ServiceDetail(); List<org.uddi.api_v3.BusinessService> apiBusinessServiceList = body.getBusinessService(); for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) { org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); modelBusinessEntity.setEntityKey(apiBusinessService.getBusinessKey()); MappingApiToModel.mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity); setOperationalInfo(em, modelBusinessService, publisher, false); em.persist(modelBusinessService); result.getBusinessService().add(apiBusinessService); validator.validateSaveServiceMax(em, modelBusinessService.getBusinessEntity().getEntityKey()); } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_SERVICE, QueryStatus.SUCCESS, procTime); return result; } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_SERVICE, QueryStatus.FAILED, procTime); throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java
public BindingDetail saveBinding(SaveBinding body) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {//from ww w . ja va2 s . c o m tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveBinding(em, body, null); BindingDetail result = new BindingDetail(); result.setListDescription(new ListDescription()); List<org.uddi.api_v3.BindingTemplate> apiBindingTemplateList = body.getBindingTemplate(); for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) { org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate(); org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService(); modelBusinessService.setEntityKey(apiBindingTemplate.getServiceKey()); MappingApiToModel.mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService); setOperationalInfo(em, modelBindingTemplate, publisher, false); em.persist(modelBindingTemplate); result.getBindingTemplate().add(apiBindingTemplate); result.getListDescription().setActualCount(result.getListDescription().getActualCount() + 1); result.getListDescription().setIncludeCount(result.getListDescription().getIncludeCount() + 1); validator.validateSaveBindingMax(em, modelBindingTemplate.getBusinessService().getEntityKey()); } tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_BINDING, QueryStatus.SUCCESS, procTime); return result; } catch (DispositionReportFaultMessage drfm) { long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(PublicationQuery.SAVE_BINDING, QueryStatus.FAILED, procTime); throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.enioka.jqm.api.HibernateClient.java
@Override public void killJob(int idJob) { // First try to cancel the JI (works if it is not already running) try {//from ww w . ja v a 2 s .c om cancelJob(idJob); return; } catch (JqmClientException e) { // Nothing to do - this is thrown if already running. Just go on, this is a standard kill. } EntityManager em = null; try { em = getEm(); em.getTransaction().begin(); JobInstance j = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_READ); if (j == null) { throw new NoResultException("Job instance does not exist or has already finished"); } jqmlogger.trace("The " + j.getState() + " job (ID: " + idJob + ")" + " will be marked for kill"); j.setState(State.KILLED); Message m = new Message(); m.setJi(idJob); m.setTextMessage("Kill attempt on the job"); em.persist(m); em.getTransaction().commit(); } catch (NoResultException e) { throw new JqmInvalidRequestException("An attempt was made to kill a job instance that did not exist."); } catch (Exception e) { throw new JqmClientException("Could not kill a job (internal error)", e); } finally { closeQuietly(em); } }
From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java
public void getTransferToken(String authInfo, KeyBag keyBag, Holder<String> nodeID, Holder<XMLGregorianCalendar> expirationTime, Holder<byte[]> opaqueToken) throws DispositionReportFaultMessage { long startTime = System.currentTimeMillis(); EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try {/*w w w . j a v a 2 s .c o m*/ tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, authInfo); new ValidateCustodyTransfer(publisher).validateGetTransferToken(em, keyBag); int transferExpirationDays = DEFAULT_TRANSFEREXPIRATION_DAYS; try { transferExpirationDays = AppConfig.getConfiguration() .getInt(Property.JUDDI_TRANSFER_EXPIRATION_DAYS); // For output nodeID.value = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID); } catch (ConfigurationException ce) { throw new FatalErrorException(new ErrorMessage("errors.configuration.Retrieval")); } String transferKey = TRANSFER_TOKEN_PREFIX + UUID.randomUUID(); org.apache.juddi.model.TransferToken transferToken = new org.apache.juddi.model.TransferToken(); transferToken.setTransferToken(transferKey); // For output opaqueToken.value = transferKey.getBytes(); GregorianCalendar gc = new GregorianCalendar(); gc.add(GregorianCalendar.DAY_OF_MONTH, transferExpirationDays); transferToken.setExpirationDate(gc.getTime()); try { DatatypeFactory df = DatatypeFactory.newInstance(); // For output expirationTime.value = df.newXMLGregorianCalendar(gc); } catch (DatatypeConfigurationException ce) { throw new FatalErrorException(new ErrorMessage("errors.Unspecified")); } List<String> keyList = keyBag.getKey(); for (String key : keyList) { TransferTokenKey tokenKey = new TransferTokenKey(transferToken, key); transferToken.getTransferKeys().add(tokenKey); } em.persist(transferToken); tx.commit(); long procTime = System.currentTimeMillis() - startTime; serviceCounter.update(CustodyTransferQuery.GET_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.jada.content.template.TemplateEngine.java
public Hashtable<String, String> updateContentComment() throws Exception { Customer customer = ContentLookupDispatchAction.getCustomer(request); if (customer == null) { return null; }//w w w.ja v a 2 s .c o m String contentNaturalKey = Utility.reEncode(getCategoryParameter(request, 2)); String commentTitle = request.getParameter("commentTitle"); commentTitle = Utility.escapeStrictHTML(commentTitle); String commentLine = request.getParameter("comment"); commentLine = Utility.escapeStrictHTML(commentLine); Hashtable<String, String> attributes = new Hashtable<String, String>(); if (Format.isNullOrEmpty(commentTitle)) { attributes.put("commentTitleMessage", getLanguage("content.error.string.required")); } if (Format.isNullOrEmpty(commentLine)) { attributes.put("commentMessage", getLanguage("content.error.string.required")); } if (attributes.size() == 0) { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); Content content = (Content) ContentDAO.loadNatural(siteDomain.getSite().getSiteId(), contentNaturalKey); Comment comment = new Comment(); comment.setCommentTitle(commentTitle); comment.setComment(commentLine); comment.setCommentRating(0); comment.setActive(Constants.VALUE_YES); String custName = customer.getCustEmail(); if (custName.length() > 20) { custName = custName.substring(0, 19); } comment.setRecCreateBy(custName); comment.setRecCreateDatetime(new Date(System.currentTimeMillis())); comment.setRecUpdateBy(custName); comment.setRecUpdateDatetime(new Date(System.currentTimeMillis())); comment.setCustomer(customer); comment.setContent(content); content.getComments().add(comment); em.persist(comment); attributes.put("commentTitle", ""); attributes.put("comment", ""); } else { attributes.put("commentTitle", commentTitle); attributes.put("comment", commentLine); } return attributes; }
From source file:com.jada.admin.site.SiteLoader.java
public void loadShippingMethod() throws Exception { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); String sql = "from ShippingMethod where siteId = :siteId order by shippingMethodId"; Query query = em.createQuery(sql); query.setParameter("siteId", Constants.SITE_SYSTEM); Iterator<?> iterator = query.getResultList().iterator(); while (iterator.hasNext()) { ShippingMethod master = (ShippingMethod) iterator.next(); ShippingMethod shippingMethod = new ShippingMethod(); shippingMethod.setSite(site);//from w w w. j a va 2 s. c o m shippingMethod.setSeqNum(master.getSeqNum()); shippingMethod.setPublished(master.getPublished()); shippingMethod.setRecUpdateBy(userId); shippingMethod.setRecUpdateDatetime(new Date(System.currentTimeMillis())); shippingMethod.setRecCreateBy(userId); shippingMethod.setRecCreateDatetime(new Date(System.currentTimeMillis())); for (ShippingMethodLanguage language : master.getShippingMethodLanguages()) { ShippingMethodLanguage shippingMethodLanguage = new ShippingMethodLanguage(); shippingMethodLanguage.setShippingMethodName(language.getShippingMethodName()); shippingMethodLanguage.setRecUpdateBy(userId); shippingMethodLanguage.setRecUpdateDatetime(new Date(System.currentTimeMillis())); shippingMethodLanguage.setRecCreateBy(userId); shippingMethodLanguage.setRecCreateDatetime(new Date(System.currentTimeMillis())); em.persist(shippingMethodLanguage); if (language.getShippingMethodLangId() .equals(master.getShippingMethodLanguage().getShippingMethodLangId())) { shippingMethod.setShippingMethodLanguage(shippingMethodLanguage); } shippingMethod.getShippingMethodLanguages().add(shippingMethodLanguage); } if (master.getShippingMethodRegions() != null) { Iterator<?> it = master.getShippingMethodRegions().iterator(); while (it.hasNext()) { ShippingMethodRegion m_shippingMethodRegion = (ShippingMethodRegion) it.next(); ShippingMethodRegion shippingMethodRegion = new ShippingMethodRegion(); shippingMethodRegion.setPublished(m_shippingMethodRegion.getPublished()); shippingMethodRegion.setRecUpdateBy(userId); shippingMethodRegion.setRecUpdateDatetime(new Date(System.currentTimeMillis())); shippingMethodRegion.setRecCreateBy(userId); shippingMethodRegion.setRecCreateDatetime(new Date(System.currentTimeMillis())); shippingMethodRegion.setShippingMethod(shippingMethod); ShippingRegion shippingRegion = getShippingRegion( m_shippingMethodRegion.getShippingRegion().getShippingRegionName()); shippingMethodRegion.setShippingRegion(shippingRegion); if (m_shippingMethodRegion.getShippingMethodRegionTypes() != null) { Iterator<?> it1 = m_shippingMethodRegion.getShippingMethodRegionTypes().iterator(); while (it1.hasNext()) { ShippingMethodRegionType m_shippingMethodRegionType = (ShippingMethodRegionType) it1 .next(); ShippingMethodRegionType shippingMethodRegionType = new ShippingMethodRegionType(); shippingMethodRegionType.setPublished(m_shippingMethodRegionType.getPublished()); shippingMethodRegionType.setRecUpdateBy(userId); shippingMethodRegionType.setRecUpdateDatetime(new Date(System.currentTimeMillis())); shippingMethodRegionType.setRecCreateBy(userId); shippingMethodRegionType.setRecCreateDatetime(new Date(System.currentTimeMillis())); shippingMethodRegionType.setShippingRegion(shippingRegion); shippingMethodRegionType.setShippingMethod(shippingMethod); shippingMethodRegionType.setShippingType(getShippingType( m_shippingMethodRegionType.getShippingType().getShippingTypeName())); ShippingRate m_shippingRate = m_shippingMethodRegionType.getShippingRate(); ShippingRate shippingRate = new ShippingRate(); PropertyUtils.copyProperties(shippingRate, m_shippingRate); shippingRate.setPublished(m_shippingRate.getPublished()); shippingRate.setRecUpdateBy(userId); shippingRate.setRecUpdateDatetime(new Date(System.currentTimeMillis())); shippingRate.setRecCreateBy(userId); shippingRate.setRecCreateDatetime(new Date(System.currentTimeMillis())); shippingMethodRegionType.setShippingRate(shippingRate); em.persist(shippingRate); em.persist(shippingMethodRegionType); shippingMethodRegion.getShippingMethodRegionTypes().add(shippingMethodRegionType); } } shippingMethod.getShippingMethodRegions().add(shippingMethodRegion); } } em.persist(shippingMethod); } }