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:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

/**
 * Creates a test resource in the database for testing purposes.
 *
 * @return persisted but detached resource
 *
 * @throws Exception if anything goes wrong
 *//*w  w w.j a  va 2  s . c  om*/
private void setupResourceEnvironment() throws Exception {
    getTransactionManager().begin();
    EntityManager em = getEntityManager();

    try {
        try {
            // Create parent resource type
            parentResourceType = new ResourceType("platform-" + System.currentTimeMillis(), "TestPlugin",
                    ResourceCategory.PLATFORM, null);
            em.persist(parentResourceType);

            // Create child resource type to parent. Artifact type lives under this resource type.
            childResourceType = new ResourceType("server-" + System.currentTimeMillis(), "TestPlugin",
                    ResourceCategory.SERVER, parentResourceType);
            em.persist(childResourceType);

            // Create artifact type under child resource type that is marked as the creation artifact type
            packageType = new PackageType();
            packageType.setName("artifact-" + System.currentTimeMillis());
            packageType.setDescription("");
            packageType.setCategory(PackageCategory.DEPLOYABLE);
            packageType.setDisplayName("TestResourceArtifact");
            packageType.setCreationData(true);
            packageType.setResourceType(childResourceType);
            em.persist(packageType);

            // Link artifact type and child resource type
            childResourceType.addPackageType(packageType);

            // Create parent resource off of which to hang created resources
            parentResource = new Resource("parent" + System.currentTimeMillis(), "name", parentResourceType);
            parentResource.setUuid("" + new Random().nextInt());
            em.persist(parentResource);
        } catch (Exception e) {
            System.out.println(e);
            getTransactionManager().rollback();
            throw e;
        }

        getTransactionManager().commit();
    } finally {
        em.close();
    }
}

From source file:org.opencastproject.userdirectory.JpaGroupRoleProvider.java

/**
 * Adds or updates a group to the persistence.
 *
 * @param group/*from   w  ww.j  a v  a 2 s . c o  m*/
 *          the group to add
 */
public void addGroup(final JpaGroup group) {
    Set<JpaRole> roles = UserDirectoryPersistenceUtil.saveRoles(group.getRoles(), emf);
    JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(group.getOrganization(), emf);

    JpaGroup jpaGroup = new JpaGroup(group.getGroupId(), organization, group.getName(), group.getDescription(),
            roles, group.getMembers());

    // Then save the jpaGroup
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaGroup foundGroup = UserDirectoryPersistenceUtil.findGroup(jpaGroup.getGroupId(),
                jpaGroup.getOrganization().getId(), emf);
        if (foundGroup == null) {
            em.persist(jpaGroup);
        } else {
            foundGroup.setName(jpaGroup.getName());
            foundGroup.setDescription(jpaGroup.getDescription());
            foundGroup.setMembers(jpaGroup.getMembers());
            foundGroup.setRoles(roles);
            em.merge(foundGroup);
        }
        tx.commit();
        messageSender.sendObjectMessage(GroupItem.GROUP_QUEUE, MessageSender.DestinationType.Queue,
                GroupItem.update(JaxbGroup.fromGroup(jpaGroup)));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java

@Override
public void importModel(InputStream inputStream, EntityManager em, Authentication authentication)
        throws ExportException {
    ObjectInputStream objectInputStream;
    em.getTransaction().begin();/*from ww w. j a v  a2s . co m*/
    try {
        objectInputStream = new ObjectInputStream(inputStream);
        OrgUnitModel orgUnitModel = (OrgUnitModel) objectInputStream.readObject();
        orgUnitModel.resetImport();
        saveOrgUnitFlexibleElement(orgUnitModel, em);

        //Set the staus to DRAFT
        orgUnitModel.setStatus(ProjectModelStatus.DRAFT);
        orgUnitModel.setOrganization(authentication.getUser().getOrganization());
        em.persist(orgUnitModel);
        em.getTransaction().commit();
    } catch (IOException e) {
        LOG.error("Model import error.", e);
    } catch (ClassNotFoundException e) {
        LOG.error("Model import error.", e);
    }
}

From source file:uk.ac.horizon.ug.mrcreator.http.CRUDServlet.java

/** Create on POST.
 * E.g. curl -d '{...}' http://localhost:8888/author/configuration/
 * @param req// w w  w  .j  a v  a2  s.co m
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
private void doCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    try {
        Object o = parseObject(req);
        if (filterByCreator) {
            String creator = getRequestCreator(req);
            setCreator(o, creator);
        }
        Key key = validateCreate(o);
        // try adding
        EntityManager em = EMF.get().createEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            if (em.find(getObjectClass(), key) != null)
                throw new RequestException(HttpServletResponse.SC_CONFLICT,
                        "object already exists (" + key + ")");
            em.persist(o);
            et.commit();
            logger.info("Added " + o);
        } finally {
            if (et.isActive())
                et.rollback();
            em.close();
        }
        resp.setCharacterEncoding(ENCODING);
        resp.setContentType(JSON_MIME_TYPE);
        Writer w = new OutputStreamWriter(resp.getOutputStream(), ENCODING);
        JSONWriter jw = new JSONWriter(w);
        listObject(jw, o);
        w.close();
    } catch (RequestException e) {
        resp.sendError(e.getErrorCode(), e.getMessage());
    } catch (Exception e) {
        logger.log(Level.WARNING, "Getting object of type " + getObjectClass(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:org.mule.module.jpa.command.Persist.java

public Object execute(EntityManager entityManager, Object entity, Map<String, Object> parameters, Boolean flush)
        throws Exception {

    logger.debug("Persisting entity: " + entity);

    entityManager.persist(entity);

    if (flush) {//w  w w  . j  av  a 2  s .c o  m
        entityManager.flush();
    }

    return entity;
}

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

public UserSession saveUserSession(UserSession userSession) {
    logger.info("Will userSession = " + userSession.getUsername());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from   www .  j  a v a2s . c  om

    FStoreUser u = entityManager.find(FStoreUser.class, userSession.getUser().getId());
    userSession.setUser(u);

    logger.info("Will userSession = " + u.toString());

    entityManager.persist(u);
    entityManager.persist(userSession);
    entityManager.flush();
    entityTransaction.commit();

    return userSession;

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void saveProperty(BakerProperty p) {
    logger.info("Will BakerProperty = " + p.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from w ww  . ja  v  a  2s. c  o  m

    entityManager.persist(p);
    entityManager.flush();
    entityTransaction.commit();

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void saveInstalledBun(InstalledBun is) {
    logger.info("Will create InstalledBun = " + is.getUuid());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//w w  w . j  a va2  s  .c  o m

    entityManager.persist(is);
    entityManager.flush();
    entityTransaction.commit();
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void saveSubscribedResource(SubscribedResource sm) {
    logger.info("Will save SubscribedResource = " + sm.getURL());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//  www  . j  a va 2  s  .  c  o m

    entityManager.persist(sm);
    entityManager.flush();
    entityTransaction.commit();

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void saveUser(BakerUser bu) {
    logger.info("Will save BakerUser = " + bu.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*ww w . j  av  a  2 s  .  c om*/

    entityManager.persist(bu);

    entityManager.flush();
    entityTransaction.commit();

}