Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

In this page you can find the example usage for javax.persistence EntityManager persist.

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Widgetprofile updateWidgetProfile(String uri, String name, String description, String icon) {
    EntityManager em = getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();/*from   w w  w .  j a v a  2  s.c  o  m*/
    Query wpQuery = em.createNamedQuery("Widgetprofile.findByUri");
    wpQuery.setParameter("uri", uri);
    Widgetprofile widgetprofile = (Widgetprofile) wpQuery.getSingleResult();
    if (widgetprofile != null) {
        widgetprofile.setName(name);
        widgetprofile.setUpdated(new Date());
        WidgetDescription desc = widgetprofile.getDescription();
        if (desc == null) {
            desc = new WidgetDescription();
            desc.setWid_id(widgetprofile.getId());
            widgetprofile.setDescription(desc);
        }
        desc.setDescription(description);
        em.persist(em.merge(widgetprofile));
    }
    em.getTransaction().commit();
    em.close();
    return widgetprofile;
}

From source file:com.jada.admin.site.SiteLoader.java

public void loadCountry() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Country country where siteId = :siteId order by countryCode";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Country master = (Country) iterator.next();
        Country country = new Country();
        PropertyUtils.copyProperties(country, master);
        country.setSite(site);/*from   ww  w. j a va2  s .c  o m*/
        country.setCountryId(null);
        country.setRecUpdateBy(userId);
        country.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        country.setRecCreateBy(userId);
        country.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        country.setShippingRegion(null);
        country.setStates(null);
        country.setTaxes(null);
        em.persist(country);
    }
}

From source file:com.jada.admin.site.SiteLoader.java

public void loadShippingType() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from ShippingType where siteId = :siteId order by shippingTypeId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingType master = (ShippingType) iterator.next();
        ShippingType shippingType = new ShippingType();
        PropertyUtils.copyProperties(shippingType, master);
        shippingType.setSite(site);/*from  w w  w.ja  va 2 s. com*/
        shippingType.setRecUpdateBy(userId);
        shippingType.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        shippingType.setRecCreateBy(userId);
        shippingType.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        shippingType.setShippingMethodRegionTypes(null);
        shippingTypes.add(shippingType);
        em.persist(shippingType);
    }
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Saves clerk(s) to the persistence layer. This method is specific to
 * jUDDI. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body/* w w  w .ja  v  a2s.c  om*/
 * @return ClerkDetail
 * @throws DispositionReportFaultMessage 
 */
public ClerkDetail saveClerk(SaveClerk body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClerk(publisher).validateSaveClerk(em, body);

        ClerkDetail result = new ClerkDetail();

        List<org.apache.juddi.api_v3.Clerk> apiClerkList = body.getClerk();
        ;
        for (org.apache.juddi.api_v3.Clerk apiClerk : apiClerkList) {

            org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk();

            MappingApiToModel.mapClerk(apiClerk, modelClerk);

            Object existingUddiEntity = em.find(modelClerk.getClass(), modelClerk.getClerkName());
            if (existingUddiEntity != null) {
                em.merge(modelClerk);
            } else {
                em.persist(modelClerk);
            }

            result.getClerk().add(apiClerk);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.rhq.enterprise.server.content.test.ContentSourceManagerBeanTest.java

private void setupTestEnvironment() throws Exception {
    getTransactionManager().begin();/*from w ww  .  j  a  v a2  s .  c  o  m*/
    EntityManager em = getEntityManager();

    try {
        try {
            architecture1 = em.find(Architecture.class, 1);
            architecture2 = em.find(Architecture.class, 2);

            resourceType1 = new ResourceType("platform-" + System.currentTimeMillis(), "TestPlugin",
                    ResourceCategory.PLATFORM, null);
            em.persist(resourceType1);

            // Add package types to resource type
            packageType1 = new PackageType();
            packageType1.setName("package1-" + System.currentTimeMillis());
            packageType1.setDescription("");
            packageType1.setCategory(PackageCategory.DEPLOYABLE);
            packageType1.setDisplayName("TestResourcePackage");
            packageType1.setCreationData(true);
            packageType1.setResourceType(resourceType1);
            em.persist(packageType1);

            packageType2 = new PackageType();
            packageType2.setName("package2-" + System.currentTimeMillis());
            packageType2.setDescription("");
            packageType2.setCategory(PackageCategory.DEPLOYABLE);
            packageType2.setDisplayName("TestResourcePackage2");
            packageType2.setCreationData(true);
            packageType2.setResourceType(resourceType1);
            em.persist(packageType2);

            packageType3 = new PackageType();
            packageType3.setName("package3-" + System.currentTimeMillis());
            packageType3.setDescription("");
            packageType3.setCategory(PackageCategory.DEPLOYABLE);
            packageType3.setDisplayName("TestResourcePackage3");
            packageType3.setCreationData(true);
            packageType3.setResourceType(resourceType1);
            em.persist(packageType3);

            packageType4 = new PackageType();
            packageType4.setName("package4-" + System.currentTimeMillis());
            packageType4.setDescription("");
            packageType4.setCategory(PackageCategory.DEPLOYABLE);
            packageType4.setDisplayName("TestResourcePackage4");
            packageType4.setCreationData(true);
            packageType4.setResourceType(resourceType1);
            em.persist(packageType4);

            resourceType1.addPackageType(packageType1);
            resourceType1.addPackageType(packageType2);
            resourceType1.addPackageType(packageType3);

            // Package 1 - Contains 2 versions
            package1 = new Package("Package1", packageType1);

            package1.addVersion(new PackageVersion(package1, "1.0.0", architecture1));
            package1.addVersion(new PackageVersion(package1, "2.0.0", architecture1));

            em.persist(package1);

            // Package 2 - Contains 2 versions
            package2 = new Package("Package2", packageType2);

            package2.addVersion(new PackageVersion(package2, "1.0.0", architecture1));
            package2.addVersion(new PackageVersion(package2, "2.0.0", architecture1));

            em.persist(package2);

            // Package 3 - Contains 1 version
            package3 = new Package("Package3", packageType3);

            package3.addVersion(new PackageVersion(package3, "1.0.0", architecture1));

            em.persist(package3);

            // Package 4 - Contains 2 versions, the first is installed
            package4 = new Package("Package4", packageType4);

            PackageVersion package4Installed = new PackageVersion(package4, "1.0.0", architecture1);
            package4.addVersion(package4Installed);
            package4.addVersion(new PackageVersion(package4, "2.0.0", architecture1));

            em.persist(package4);

            // Package 5 - Contains 1 version, it is installed
            package5 = new Package("Package5", packageType4);

            PackageVersion package5Installed = new PackageVersion(package5, "1.0.0", architecture1);
            package5.addVersion(package5Installed);

            em.persist(package5);

            // Create resource against which we'll merge the discovery report
            resource1 = new Resource("parent" + System.currentTimeMillis(), "name", resourceType1);
            resource1.setUuid("" + new Random().nextInt());
            em.persist(resource1);

            // Install packages on the resource
            installedPackage1 = new InstalledPackage();
            installedPackage1.setResource(resource1);
            installedPackage1.setPackageVersion(package4Installed);
            resource1.addInstalledPackage(installedPackage1);

            installedPackage2 = new InstalledPackage();
            installedPackage2.setResource(resource1);
            installedPackage2.setPackageVersion(package4Installed);
            resource1.addInstalledPackage(installedPackage2);

            installedPackage1.setResource(resource1);
            installedPackage2.setResource(resource1);

            getTransactionManager().commit();
        } catch (Exception e) {
            e.printStackTrace();
            getTransactionManager().rollback();
            throw e;
        }
    } finally {
        em.close();
    }
}

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

@Override
@SuppressWarnings("unchecked")
public Set<Entity> commit(CommitContext context) {
    if (log.isDebugEnabled())
        log.debug("commit: commitInstances=" + context.getCommitInstances() + ", removeInstances="
                + context.getRemoveInstances());

    Set<Entity> res = new HashSet<>();
    List<Entity> persisted = new ArrayList<>();
    List<BaseGenericIdEntity> identityEntitiesToStoreDynamicAttributes = new ArrayList<>();
    List<CategoryAttributeValue> attributeValuesToRemove = new ArrayList<>();

    try (Transaction tx = persistence.createTransaction(storeName)) {
        EntityManager em = persistence.getEntityManager(storeName);
        checkPermissions(context);//from www  .j  a  va  2s  .  c o  m

        if (!context.isSoftDeletion())
            em.setSoftDeletion(false);

        persistence.getEntityManagerContext(storeName).setDbHints(context.getDbHints());

        List<BaseGenericIdEntity> entitiesToStoreDynamicAttributes = new ArrayList<>();

        // persist new
        for (Entity entity : context.getCommitInstances()) {
            if (PersistenceHelper.isNew(entity)) {
                attributeSecurity.beforePersist(entity);
                em.persist(entity);
                checkOperationPermitted(entity, ConstraintOperationType.CREATE);
                if (!context.isDiscardCommitted()) {
                    entityFetcher.fetch(entity, getViewFromContextOrNull(context, entity), true);
                    res.add(entity);
                }
                persisted.add(entity);

                if (entityHasDynamicAttributes(entity)) {
                    if (entity instanceof BaseDbGeneratedIdEntity) {
                        identityEntitiesToStoreDynamicAttributes.add((BaseGenericIdEntity) entity);
                    } else {
                        entitiesToStoreDynamicAttributes.add((BaseGenericIdEntity) entity);
                    }
                }
            }
        }

        // merge the rest - instances can be detached or not
        for (Entity entity : context.getCommitInstances()) {
            if (!PersistenceHelper.isNew(entity)) {
                if (isAuthorizationRequired()) {
                    security.checkSecurityToken(entity, null);
                }
                security.restoreSecurityStateAndFilteredData(entity);
                attributeSecurity.beforeMerge(entity);

                Entity merged = em.merge(entity);
                entityFetcher.fetch(merged, getViewFromContext(context, entity));
                attributeSecurity.afterMerge(merged);

                checkOperationPermitted(merged, ConstraintOperationType.UPDATE);
                if (!context.isDiscardCommitted()) {
                    res.add(merged);
                }
                if (entityHasDynamicAttributes(entity)) {
                    BaseGenericIdEntity originalBaseGenericIdEntity = (BaseGenericIdEntity) entity;
                    BaseGenericIdEntity mergedBaseGenericIdEntity = (BaseGenericIdEntity) merged;
                    mergedBaseGenericIdEntity
                            .setDynamicAttributes(originalBaseGenericIdEntity.getDynamicAttributes());
                    entitiesToStoreDynamicAttributes.add(mergedBaseGenericIdEntity);
                }
            }
        }

        for (BaseGenericIdEntity entity : entitiesToStoreDynamicAttributes) {
            dynamicAttributesManagerAPI.storeDynamicAttributes(entity);
        }

        // remove
        for (Entity entity : context.getRemoveInstances()) {
            if (isAuthorizationRequired()) {
                security.checkSecurityToken(entity, null);
            }
            security.restoreSecurityStateAndFilteredData(entity);

            Entity e;
            if (entity instanceof SoftDelete) {
                attributeSecurity.beforeMerge(entity);
                e = em.merge(entity);
                entityFetcher.fetch(e, getViewFromContext(context, entity));
                attributeSecurity.afterMerge(e);
            } else {
                e = em.merge(entity);
            }
            checkOperationPermitted(e, ConstraintOperationType.DELETE);
            em.remove(e);
            if (!context.isDiscardCommitted()) {
                res.add(e);
            }

            if (entityHasDynamicAttributes(entity)) {
                Map<String, CategoryAttributeValue> dynamicAttributes = ((BaseGenericIdEntity) entity)
                        .getDynamicAttributes();

                //dynamicAttributes checked for null in entityHasDynamicAttributes()
                //noinspection ConstantConditions
                for (CategoryAttributeValue categoryAttributeValue : dynamicAttributes.values()) {
                    if (!PersistenceHelper.isNew(categoryAttributeValue)) {
                        if (Stores.isMain(storeName)) {
                            em.remove(categoryAttributeValue);
                        } else {
                            attributeValuesToRemove.add(categoryAttributeValue);
                        }
                        if (!context.isDiscardCommitted()) {
                            res.add(categoryAttributeValue);
                        }
                    }
                }
            }

            if (!context.isDiscardCommitted() && isAuthorizationRequired()
                    && userSessionSource.getUserSession().hasConstraints()) {
                security.filterByConstraints(res);
            }
        }

        tx.commit();
    }

    if (!attributeValuesToRemove.isEmpty()) {
        try (Transaction tx = persistence.createTransaction()) {
            EntityManager em = persistence.getEntityManager();
            for (CategoryAttributeValue entity : attributeValuesToRemove) {
                em.remove(entity);
            }
            tx.commit();
        }
    }

    try (Transaction tx = persistence.createTransaction(storeName)) {
        for (BaseGenericIdEntity entity : identityEntitiesToStoreDynamicAttributes) {
            dynamicAttributesManagerAPI.storeDynamicAttributes(entity);
        }
        tx.commit();
    }

    if (!context.isDiscardCommitted() && isAuthorizationRequired()
            && userSessionSource.getUserSession().hasConstraints()) {
        security.applyConstraints(res);
    }

    if (!context.isDiscardCommitted()) {
        for (Entity entity : res) {
            if (!persisted.contains(entity)) {
                attributeSecurity.afterCommit(entity);
            }
        }
        updateReferences(persisted, res);
    }

    return res;
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

public TModelDetail saveTModel(SaveTModel body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w ww.  j a  v  a  2 s . c om*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateSaveTModel(em, body, null);

        TModelDetail result = new TModelDetail();

        List<org.uddi.api_v3.TModel> apiTModelList = body.getTModel();
        for (org.uddi.api_v3.TModel apiTModel : apiTModelList) {

            org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel();

            MappingApiToModel.mapTModel(apiTModel, modelTModel);

            setOperationalInfo(em, modelTModel, publisher);

            em.persist(modelTModel);

            result.getTModel().add(apiTModel);

        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SAVE_TMODEL, QueryStatus.SUCCESS, procTime);

        return result;
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SAVE_TMODEL, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Saves publisher(s) to the persistence layer. This method is specific
 * to jUDDI. Administrative privilege required.
 *
 * @param body//from w  w w .j a v  a 2  s .c o m
 * @return PublisherDetail
 * @throws DispositionReportFaultMessage
 */
public PublisherDetail savePublisher(SavePublisher body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateSavePublisher(em, body);

        PublisherDetail result = new PublisherDetail();

        List<org.apache.juddi.api_v3.Publisher> apiPublisherList = body.getPublisher();
        for (org.apache.juddi.api_v3.Publisher apiPublisher : apiPublisherList) {

            org.apache.juddi.model.Publisher modelPublisher = new org.apache.juddi.model.Publisher();

            MappingApiToModel.mapPublisher(apiPublisher, modelPublisher);

            Object existingUddiEntity = em.find(modelPublisher.getClass(), modelPublisher.getAuthorizedName());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelPublisher);

            result.getPublisher().add(apiPublisher);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.bubblecloud.ilves.comment.CommentAddComponent.java

/**
 * The default constructor which instantiates Vaadin
 * component hierarchy./*from   w w  w.  j a v  a  2  s. co  m*/
 */
public CommentAddComponent() {

    final User user = DefaultSiteUI.getSecurityProvider().getUserFromSession();

    final String contextPath = VaadinService.getCurrentRequest().getContextPath();
    final Site site = Site.getCurrent();

    final Company company = site.getSiteContext().getObject(Company.class);
    final EntityManager entityManager = site.getSiteContext().getObject(EntityManager.class);

    final Panel panel = new Panel(site.localize("panel-add-comment"));
    setCompositionRoot(panel);

    final VerticalLayout mainLayout = new VerticalLayout();
    panel.setContent(mainLayout);
    mainLayout.setMargin(true);
    mainLayout.setSpacing(true);

    final TextArea commentMessageField = new TextArea(site.localize("field-comment-message"));
    mainLayout.addComponent(commentMessageField);
    commentMessageField.setWidth(100, Unit.PERCENTAGE);
    commentMessageField.setRows(3);
    commentMessageField.setMaxLength(255);

    final Button addCommentButton = new Button(site.localize("button-add-comment"));
    mainLayout.addComponent(addCommentButton);
    if (user == null) {
        commentMessageField.setEnabled(false);
        commentMessageField.setInputPrompt(site.localize("message-please-login-to-comment"));
        addCommentButton.setEnabled(false);
    }

    addCommentButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            final String commentMessage = commentMessageField.getValue();
            if (StringUtils.isEmpty(commentMessage)) {
                return;
            }
            final Comment comment = new Comment(company, user, contextPath, commentMessage);
            entityManager.getTransaction().begin();
            try {
                entityManager.persist(comment);
                entityManager.getTransaction().commit();
                commentMessageField.setValue("");
                if (commentListComponent != null) {
                    commentListComponent.refresh();
                }
            } finally {
                if (entityManager.getTransaction().isActive()) {
                    entityManager.getTransaction().rollback();
                }
            }
        }
    });

}

From source file:com.headissue.pigeon.setup.DemoSetup.java

public DemoSetup() {
    setPersistenceConfig(new PersistenceConfig() {
        @Override//from  ww  w  .  j a v a 2 s .  c  o  m
        public String getUnitName() {
            return "pigeon-demo";
        }

        @Override
        public void initializeDatabase(EntityManager _manager) {
            Survey _survey = new Survey();
            _survey.setName("Default Survey");
            _survey.setCreateAt(new Date());
            _survey.setUpdateAt(new Date());
            _survey.setStatus(SurveyStatus.ENABLED);
            Question q1 = new Question();
            q1.setTitle("Default");
            q1.setText("A Yes / No Question");
            q1.setType(QuestionType.BOOL);
            q1.addAnswer("Yes", 1);
            q1.addAnswer("No", 2);
            _survey.addQuestion(q1);
            Question q2 = new Question();
            q2.setTitle("Default");
            q2.setText("Choose Question");
            q2.setType(QuestionType.CHOICE);
            q2.addAnswer("A", 1);
            q2.addAnswer("B", 2);
            q2.addAnswer("C", 3);
            q2.addAnswer("D", 4);
            _survey.addQuestion(q2);
            Question q3 = new Question();
            q3.setTitle("Default");
            q3.setText("Multiple Question");
            q3.setType(QuestionType.MULTIPLE);
            q3.addAnswer("1", 1);
            q3.addAnswer("2", 2);
            q3.addAnswer("3", 3);
            q3.addAnswer("4", 4);
            _survey.addQuestion(q3);
            Question q4 = new Question();
            q4.setTitle("Default");
            q4.setText("Free Text Question");
            q4.setType(QuestionType.FREE);
            _survey.addQuestion(q4);
            _manager.getTransaction().begin();
            _manager.persist(_survey);
            _manager.getTransaction().commit();
            LogUtils.info(log, "Initialize the default survey (id=%s)", _survey.getId());
        }
    });
}