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:com.chiralbehaviors.CoRE.time.Interval.java

@Override
public void link(Relationship r, Interval child, Agency updatedBy, Agency inverseSoftware, EntityManager em) {
    assert r != null : "Relationship cannot be null";
    assert child != null;
    assert updatedBy != null;
    assert em != null;

    IntervalNetwork link = new IntervalNetwork(this, r, child, updatedBy);
    em.persist(link);
    IntervalNetwork inverse = new IntervalNetwork(child, r.getInverse(), this, inverseSoftware);
    em.persist(inverse);/*from w  w  w .  java 2  s  . co  m*/
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImpl.java

@Override
@Transactional// ww w  . java  2s  . co  m
public void deleteSession(Session session) {
    Validate.notNull(session, "session can not be null");

    final SessionImpl sessionImpl = this.getSession(session.getSessionId());
    final EntityManager entityManager = this.getEntityManager();

    final ConferenceUserImpl creator = sessionImpl.getCreator();
    creator.getOwnedSessions().remove(sessionImpl);
    entityManager.persist(creator);

    for (final ConferenceUserImpl user : sessionImpl.getChairs()) {
        user.getChairedSessions().remove(sessionImpl);
        entityManager.persist(user);
    }

    for (final ConferenceUserImpl user : sessionImpl.getNonChairs()) {
        user.getNonChairedSessions().remove(sessionImpl);
        entityManager.persist(user);
    }

    entityManager.remove(sessionImpl);
}

From source file:org.drools.container.spring.beans.persistence.VariablePersistenceStrategyTest.java

@Test
public void testPersistenceVariables() throws NamingException, NotSupportedException, SystemException,
        IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    MyEntity myEntity = new MyEntity("This is a test Entity with annotation in fields");
    MyEntityMethods myEntityMethods = new MyEntityMethods("This is a test Entity with annotations in methods");
    MyEntityOnlyFields myEntityOnlyFields = new MyEntityOnlyFields(
            "This is a test Entity with annotations in fields and without accesors methods");
    MyVariableSerializable myVariableSerializable = new MyVariableSerializable(
            "This is a test SerializableObject");
    EntityManager em = ((EntityManagerFactory) ctx.getBean("myEmf")).createEntityManager();

    em.getTransaction().begin();//from   w  w  w .  j a  v  a 2 s .co m
    em.persist(myEntity);
    em.persist(myEntityMethods);
    em.persist(myEntityOnlyFields);
    em.getTransaction().commit();
    em.close();

    log.info("---> get bean jpaSingleSessionCommandService");
    StatefulKnowledgeSession service = (StatefulKnowledgeSession) ctx.getBean("jpaSingleSessionCommandService");

    int sessionId = service.getId();
    log.info("---> created SingleSessionCommandService id: " + sessionId);

    log.info("### Starting process ###");
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("x", "SomeString");
    parameters.put("y", myEntity);
    parameters.put("m", myEntityMethods);
    parameters.put("f", myEntityOnlyFields);
    parameters.put("z", myVariableSerializable);
    WorkflowProcessInstance processInstance = (WorkflowProcessInstance) service
            .startProcess("com.sample.ruleflow", parameters);
    log.info("Started process instance {}", processInstance.getId());

    TestWorkItemHandler handler = TestWorkItemHandler.getInstance();
    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);
    service.dispose();

    EntityManagerFactory emf = (EntityManagerFactory) ctx.getBean("myEmf");

    //        List< ? > result = emf.createEntityManager().createQuery( "select i from VariableInstanceInfo i" ).getResultList();
    //        assertEquals( 5,
    //                      result.size() );
    log.info("### Retrieving process instance ###");

    Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(EnvironmentName.TRANSACTION_MANAGER, ctx.getBean("txManager"));
    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] {
            //  new JPAPlaceholderResolverStrategy(env),
            new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) });

    KnowledgeStoreService kstore = (KnowledgeStoreService) ctx.getBean("kstore1");
    KnowledgeBase kbase1 = (KnowledgeBase) ctx.getBean("kbase1");
    service = kstore.loadStatefulKnowledgeSession(sessionId, kbase1, null, env);

    processInstance = (WorkflowProcessInstance) service.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    assertNotNull(processInstance);
    assertEquals("SomeString", processInstance.getVariable("x"));
    assertEquals("This is a test Entity with annotation in fields",
            ((MyEntity) processInstance.getVariable("y")).getTest());
    assertEquals("This is a test Entity with annotations in methods",
            ((MyEntityMethods) processInstance.getVariable("m")).getTest());
    assertEquals("This is a test Entity with annotations in fields and without accesors methods",
            ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
    assertEquals("This is a test SerializableObject",
            ((MyVariableSerializable) processInstance.getVariable("z")).getText());
    assertNull(processInstance.getVariable("a"));
    assertNull(processInstance.getVariable("b"));
    assertNull(processInstance.getVariable("c"));

    service.dispose();

    //        log.info("### Completing first work item ###");
    //        ksession.getWorkItemManager().completeWorkItem( workItem.getId(), null );
    //
    //        workItem = handler.getWorkItem();
    //        assertNotNull( workItem );
    //        
    //        log.info("### Retrieving variable instance infos ###");
    //        result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
    //        assertEquals(8, result.size());
    //        for (Object o: result) {
    //            assertTrue(VariableInstanceInfo.class.isAssignableFrom(o.getClass()));
    //            log.info(o);
    //        }
    //        
    //        log.info("### Retrieving process instance ###");
    //        ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    //        processInstance = (WorkflowProcessInstance)
    //            ksession.getProcessInstance(processInstance.getId());
    //        assertNotNull(processInstance);
    //        assertEquals("SomeString", processInstance.getVariable("x"));
    //        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
    //        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
    //        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
    //        assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
    //        assertEquals("Some new String", processInstance.getVariable("a"));
    //        assertEquals("This is a new test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
    //        assertEquals("This is a new test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
    //        log.info("### Completing second work item ###");
    //        ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    //
    //        workItem = handler.getWorkItem();
    //        assertNotNull(workItem);
    //        
    //        result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
    //        assertEquals(8, result.size());
    //        
    //        log.info("### Retrieving process instance ###");
    //        ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    //        processInstance = (WorkflowProcessInstance)
    //            ksession.getProcessInstance(processInstance.getId());
    //        assertNotNull(processInstance);
    //        assertEquals("SomeString", processInstance.getVariable("x"));
    //        assertEquals("This is a test Entity with annotation in fields", ((MyEntity) processInstance.getVariable("y")).getTest());
    //        assertEquals("This is a test Entity with annotations in methods", ((MyEntityMethods) processInstance.getVariable("m")).getTest());
    //        assertEquals("This is a test Entity with annotations in fields and without accesors methods", ((MyEntityOnlyFields) processInstance.getVariable("f")).test);
    //        assertEquals("This is a test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("z")).getText());
    //        assertEquals("Some changed String", processInstance.getVariable("a"));
    //        assertEquals("This is a changed test Entity", ((MyEntity) processInstance.getVariable("b")).getTest());
    //        assertEquals("This is a changed test SerializableObject", ((MyVariableSerializable) processInstance.getVariable("c")).getText());
    //        log.info("### Completing third work item ###");
    //        ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    //
    //        workItem = handler.getWorkItem();
    //        assertNull(workItem);
    //        
    //        result = emf.createEntityManager().createQuery("select i from VariableInstanceInfo i").getResultList();
    //        //This was 6.. but I change it to 0 because all the variables will go away with the process instance..
    //        //we need to change that to leave the variables there??? 
    //        assertEquals(0, result.size());
    //
    //        ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    //        processInstance = (WorkflowProcessInstance)
    //            ksession.getProcessInstance(processInstance.getId());
    //        assertNull(processInstance);
}

From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java

@Override
public StoredQuery persistStoredQuery(final StoredQuery srampStoredQuery) throws ArtificerException {
    // Validate the name
    if (StringUtils.isBlank(srampStoredQuery.getQueryName())) {
        throw ArtificerConflictException.storedQueryConflict();
    }//  w ww  .jav a 2s  .c  o  m

    // Check if a stored query with the given name already exists.
    try {
        getStoredQuery(srampStoredQuery.getQueryName());
        throw ArtificerConflictException.storedQueryConflict(srampStoredQuery.getQueryName());
    } catch (ArtificerNotFoundException e) {
        // do nothing -- success
    }

    new HibernateUtil.HibernateTask<Void>() {
        @Override
        protected Void doExecute(EntityManager entityManager) throws Exception {
            ArtificerStoredQuery artificerStoredQuery = HibernateEntityFactory.storedQuery(srampStoredQuery);
            entityManager.persist(artificerStoredQuery);
            return null;
        }
    }.execute();
    return srampStoredQuery;
}

From source file:com.enioka.jqm.api.HibernateClient.java

private static RuntimeParameter createJobParameter(String key, String value, EntityManager em) {
    RuntimeParameter j = new RuntimeParameter();

    j.setKey(key);/*from  w  w w .  j  a v a 2 s.c o  m*/
    j.setValue(value);

    em.persist(j);
    return j;
}

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

private void setupTestEnvironment() throws Exception {
    getTransactionManager().begin();//from  w  w  w.  jav a 2  s .  co  m
    EntityManager em = getEntityManager();

    try {
        try {
            architecture = em.find(Architecture.class, 1);

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

            // Create resource against which we'll be retrieving packages
            resource = new Resource("parent" + System.currentTimeMillis(), "name", resourceType);
            resource.setUuid("" + new Random().nextInt());
            resource.setVersion("1.0");
            em.persist(resource);

            // Product versions
            productVersion1 = new ProductVersion();
            productVersion1.setVersion("1.0");
            productVersion1.setResourceType(resourceType);
            em.persist(productVersion1);

            resource.setProductVersion(productVersion1);

            productVersion2 = new ProductVersion();
            productVersion2.setVersion("2.0");
            productVersion2.setResourceType(resourceType);
            em.persist(productVersion2);

            // 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(resourceType);
            em.persist(packageType1);

            resourceType.addPackageType(packageType1);

            // Package 1 - No product versions specified
            package1 = new Package("Package1", packageType1);
            PackageVersion packageVersion1 = new PackageVersion(package1, "1.0.0", architecture);
            package1.addVersion(packageVersion1);

            em.persist(package1);

            // Package 2 - Has list of product versions that contains the resource's version
            package2 = new Package("Package2", packageType1);
            PackageVersion packageVersion2 = new PackageVersion(package2, "1.0.0", architecture);
            ProductVersionPackageVersion pvpv1 = packageVersion2.addProductVersion(productVersion1);
            ProductVersionPackageVersion pvpv2 = packageVersion2.addProductVersion(productVersion2);
            package2.addVersion(packageVersion2);

            em.persist(package2);
            em.persist(pvpv1);
            em.persist(pvpv2);

            // Package 3 - Has list of product versions where the resource version is not included
            package3 = new Package("Package3", packageType1);
            PackageVersion packageVersion3 = new PackageVersion(package3, "1.0.0", architecture);
            ProductVersionPackageVersion pvpv3 = packageVersion3.addProductVersion(productVersion2);
            package3.addVersion(packageVersion3);

            em.persist(package3);
            em.persist(pvpv3);

            // Package 4 - No product version restriction, but already installed on the resource
            package4 = new Package("Package4", packageType1);
            PackageVersion packageVersion4 = new PackageVersion(package4, "1.0.0", architecture);
            package4.addVersion(packageVersion4);

            em.persist(package4);

            // Wire up the repo to the resource and add all of these packages to it
            repo1 = new Repo("repo-" + RandomStringUtils.randomNumeric(6));
            em.persist(repo1);

            repoPackageVersion1 = repo1.addPackageVersion(packageVersion1);
            repoPackageVersion2 = repo1.addPackageVersion(packageVersion2);
            repoPackageVersion3 = repo1.addPackageVersion(packageVersion3);
            repoPackageVersion4 = repo1.addPackageVersion(packageVersion4);

            em.persist(repoPackageVersion1);
            em.persist(repoPackageVersion2);
            em.persist(repoPackageVersion3);
            em.persist(repoPackageVersion4);

            resourceRepo1 = repo1.addResource(resource);
            em.persist(resourceRepo1);

            // Subscribe the resource to a second repo to make sure the joins won't duplicate stuff
            repo2 = new Repo("test-" + RandomStringUtils.randomNumeric(6));
            em.persist(repo2);

            resourceRepo2 = repo2.addResource(resource);
            em.persist(resourceRepo2);

            installedPackage1 = new InstalledPackage();
            installedPackage1.setResource(resource);
            installedPackage1.setPackageVersion(packageVersion4);
            resource.addInstalledPackage(installedPackage1);

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

From source file:test.unit.be.fedict.eid.dss.XmlSchemaManagerBeanTest.java

@Test
public void testAdd2() throws Exception {
    // setup/*from w  w  w . j  a  v a2  s  . co  m*/
    XmlSchemaManagerBean testedInstance = new XmlSchemaManagerBean();
    InputStream xsdInputStream = XmlSchemaManagerBeanTest.class.getResourceAsStream("/example.xsd");
    byte[] xsd = IOUtils.toByteArray(xsdInputStream);
    InputStream xsd2InputStream = XmlSchemaManagerBeanTest.class.getResourceAsStream("/example2.xsd");
    EntityManager mockEntityManager = EasyMock.createMock(EntityManager.class);
    injectPersistenceContext(mockEntityManager, testedInstance);

    XmlSchemaEntity exampleXmlSchemaEntity = new XmlSchemaEntity("", "1.0", xsd);

    // expectations
    EasyMock.expect(mockEntityManager.find(XmlSchemaEntity.class, "urn:be:fedict:eid:dss:example"))
            .andReturn(exampleXmlSchemaEntity);
    EasyMock.expect(mockEntityManager.find(XmlSchemaEntity.class, "urn:be:fedict:eid:dss:example2"))
            .andReturn(null);

    Capture<XmlSchemaEntity> persistCapture = new Capture<XmlSchemaEntity>();
    mockEntityManager.persist(EasyMock.capture(persistCapture));

    // prepare
    EasyMock.replay(mockEntityManager);

    // operate
    testedInstance.add("1.0", xsd2InputStream);

    // verify
    EasyMock.verify(mockEntityManager);
    XmlSchemaEntity resultEntity = persistCapture.getValue();
    assertEquals("urn:be:fedict:eid:dss:example2", resultEntity.getNamespace());
    assertEquals("1.0", resultEntity.getRevision());
}

From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationCollectionService.java

/**
 * Register a new application.//from w ww  .j  a  v  a 2 s  .  c o m
 *
 * @param application The application to register
 * @return The registered application
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Application createApplication(final Application application) {
    if (application.getInfrastructureIds() == null || application.getInfrastructureIds().isEmpty()) {
        throw new BadRequestException();
    }
    Date now = new Date();
    application.setDateCreated(now);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        List<Infrastructure> lstInfra = new LinkedList<>();
        for (String infraId : application.getInfrastructureIds()) {
            Infrastructure infra = em.find(Infrastructure.class, infraId);
            if (infra == null) {
                throw new BadRequestException();
            }
            lstInfra.add(infra);
        }
        application.setInfrastructures(lstInfra);
        em.persist(application);
        et.commit();
        log.debug("New application registered: " + application.getId());
    } catch (BadRequestException re) {
        throw re;
    } catch (RuntimeException re) {
        log.error("Impossible to create the application");
        log.error(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return application;
}

From source file:org.nuxeo.ecm.activity.ActivityStreamServiceImpl.java

protected void addActivity(EntityManager em, Activity activity) {
    try {/*from   w  w  w. j a  v a 2 s .com*/
        localEntityManager.set(em);
        em.persist(activity);
        for (ActivityStreamFilter filter : activityStreamFilters.values()) {
            if (filter.isInterestedIn(activity)) {
                filter.handleNewActivity(this, activity);
            }
        }
    } finally {
        localEntityManager.remove();
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void saveProduct(Product prod) {
    logger.info("Will save Product = " + prod.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/* w  w  w  . jav a 2 s.c  om*/
    entityManager.persist(prod);
    entityManager.flush();
    entityTransaction.commit();

}