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.openejb.persistence.OpenJpaProviderTest.java

public void testOpenJpaProvider() throws Exception {
    System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, "org.openejb.persistence");

    PersistenceDeployer deployer = new PersistenceDeployer(new TestDataSourceResolver());

    Map<String, EntityManagerFactory> map = deployer.deploy(Thread.currentThread().getContextClassLoader());

    EntityManagerFactory emf = map.get("openjpa-test-unit");
    assertNotNull("EntityManagerFactory", emf);

    EntityManager em = emf.createEntityManager();
    assertNotNull("EntityManager", em);

    em.getTransaction().begin();//from  w  w  w.j av a  2  s .c  o  m
    em.persist(new AllFieldTypes());
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    em.createQuery("delete from AllFieldTypes").executeUpdate();
    em.getTransaction().commit();
    em.close();
    emf.close();
}

From source file:org.apache.juddi.config.Install.java

/**
 * Public convenience method that allows one to install additional Publishers via a Publisher structure.
 * /*from   w ww. ja  v  a2  s. co m*/
 * @param em - the entity manager to the juddi model
 * @param fileName - name of Publisher xml file
 * @return UddiEntityPublisher object, can be any UDDIEntity
 * @throws JAXBException
 * @throws DispositionReportFaultMessage
 * @throws IOException
 * @throws ConfigurationException 
 */
public static UddiEntityPublisher installPublisher(EntityManager em, String fileName, Configuration config)
        throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException {

    org.apache.juddi.api_v3.Publisher apiPub = (org.apache.juddi.api_v3.Publisher) buildInstallEntity(fileName,
            "org.apache.juddi.api_v3", config);
    if (apiPub == null)
        return null;
    org.apache.juddi.model.Publisher modelPub = new org.apache.juddi.model.Publisher();
    MappingApiToModel.mapPublisher(apiPub, modelPub);
    em.persist(modelPub);
    return modelPub;
}

From source file:net.anthonychaves.bookmarks.service.TokenService.java

public String setupNewLoginToken(User user) {
    PersistentLoginToken token = new PersistentLoginToken();
    EntityManager em = emf.createEntityManager();

    em.getTransaction().begin();//from  ww  w  .  j  a va  2 s.  c  o  m
    User u = em.find(User.class, user.getId());
    token.setUser(u);
    em.persist(token);
    em.getTransaction().commit();

    return token.getId();
}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Creates or updates metadata common to all nodes: default queue, global parameters, roles...<br>
 * It is idempotent. It also has the effect of making broken metadata viable again.
 *//*  w  w w .j ava2s.c o  m*/
static void updateConfiguration(EntityManager em) {
    em.getTransaction().begin();

    // Default queue
    Queue q = null;
    long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu").getSingleResult();
    if (i == 0L) {
        q = new Queue();
        q.setDefaultQueue(true);
        q.setDescription("default queue");
        q.setTimeToLive(1024);
        q.setName("DEFAULT");
        em.persist(q);

        jqmlogger.info("A default queue was created in the configuration");
    } else {
        try {
            q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class)
                    .getSingleResult();
            jqmlogger.info("Default queue is named " + q.getName());
        } catch (NonUniqueResultException e) {
            // Faulty configuration, but why not
            q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0);
            q.setDefaultQueue(true);
            jqmlogger.info("Queue " + q.getName()
                    + " was modified to become the default queue as there were mutliple default queue");
        } catch (NoResultException e) {
            // Faulty configuration, but why not
            q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0);
            q.setDefaultQueue(true);
            jqmlogger.warn("Queue  " + q.getName()
                    + " was modified to become the default queue as there was no default queue");
        }
    }

    // Global parameters
    initSingleParam("mavenRepo", "http://repo1.maven.org/maven2/", em);
    initSingleParam(Constants.GP_DEFAULT_CONNECTION_KEY, Constants.GP_JQM_CONNECTION_ALIAS, em);
    initSingleParam("logFilePerLaunch", "true", em);
    initSingleParam("internalPollingPeriodMs", "60000", em);
    initSingleParam("disableWsApi", "false", em);
    initSingleParam("enableWsApiSsl", "false", em);
    initSingleParam("enableWsApiAuth", "true", em);
    initSingleParam("enableInternalPki", "true", em);

    // Roles
    RRole adminr = createRoleIfMissing(em, "administrator", "all permissions without exception", "*:*");
    createRoleIfMissing(em, "config admin",
            "can read and write all configuration, except security configuration", "node:*", "queue:*",
            "qmapping:*", "jndi:*", "prm:*", "jd:*");
    createRoleIfMissing(em, "config viewer", "can read all configuration except for security configuration",
            "node:read", "queue:read", "qmapping:read", "jndi:read", "prm:read", "jd:read");
    createRoleIfMissing(em, "client",
            "can use the full client API except reading logs, files and altering position", "node:read",
            "queue:read", "job_instance:*", "jd:read");
    createRoleIfMissing(em, "client power user", "can use the full client API", "node:read", "queue:read",
            "job_instance:*", "jd:read", "logs:read", "queue_position:create", "files:read");
    createRoleIfMissing(em, "client read only", "can query job instances and get their files", "queue:read",
            "job_instance:read", "logs:read", "files:read");

    // Users
    createUserIfMissing(em, "root", "all powerful user", adminr);

    // Mail session
    i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn")
            .setParameter("nn", "mail/default").getSingleResult();
    if (i == 0) {
        HashMap<String, String> prms = new HashMap<String, String>();
        prms.put("smtpServerHost", "smtp.gmail.com");

        JndiObjectResource res = new JndiObjectResource();
        res.setAuth(null);
        res.setDescription("default parameters used to send e-mails");
        res.setFactory("com.enioka.jqm.providers.MailSessionFactory");
        res.setName("mail/default");
        res.setType("javax.mail.Session");
        res.setSingleton(true);
        em.persist(res);

        JndiObjectResourceParameter prm = new JndiObjectResourceParameter();
        prm.setKey("smtpServerHost");
        prm.setValue("smtp.gmail.com");
        res.getParameters().add(prm);
        prm.setResource(res);
    }

    // Done
    em.getTransaction().commit();
}

From source file:org.spc.ofp.tubs.domain.purseseine.TripRepository.java

public void save(final PurseSeineTrip trip) {
    final EntityManager mgr = emf.createEntityManager();
    final EntityTransaction xa = mgr.getTransaction();
    try {/*from   w  w  w .j a  va2 s.co  m*/
        xa.begin();
        mgr.persist(trip);
        mgr.flush();
        xa.commit();
        mgr.refresh(trip);
    } catch (Exception ex) {
        if (xa.isActive()) {
            xa.rollback();
        }
    } finally {
        mgr.close();
    }
}

From source file:org.sonar.jpa.session.MemoryDatabaseConnector.java

protected void setupSchemaVersion(int version) {
    SchemaMigration migration = new SchemaMigration();
    migration.setVersion(version);/*from w w  w  . j av  a  2s  . co  m*/
    EntityManager manager = null;
    try {
        manager = createEntityManager();
        manager.getTransaction().begin();
        manager.persist(migration);
        manager.getTransaction().commit();

    } finally {
        if (manager != null) {
            manager.close();
        }
    }
}

From source file:io.kloudwork.controller.LoginController.java

public String postRegister(Request request, Response response) throws IOException, FileUploadException {

    String salt = BCrypt.gensalt();
    String hash = BCrypt.hashpw(request.queryParams("password"), salt);

    User user = new User();
    user.setUsername(request.queryParams("username"));
    user.setPassword(hash);/*  ww  w  . ja  v  a2  s.  co m*/

    EntityManager entityManager = Container.getInstance().getEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist(user);
    entityManager.getTransaction().commit();
    return "registered";
}

From source file:org.apache.falcon.jdbc.BacklogMetricStore.java

public void addInstance(String entityName, String cluster, Date nominalTime, EntityType entityType) {
    BacklogMetricBean backlogMetricBean = new BacklogMetricBean();
    backlogMetricBean.setClusterName(cluster);
    backlogMetricBean.setEntityName(entityName);
    backlogMetricBean.setNominalTime(nominalTime);
    backlogMetricBean.setEntityType(entityType.name());
    EntityManager entityManager = getEntityManager();
    try {/* w w  w .  j  a  v  a 2s  .  co  m*/
        beginTransaction(entityManager);
        entityManager.persist(backlogMetricBean);
    } finally {
        commitAndCloseTransaction(entityManager);
    }
}

From source file:org.apache.juddi.config.Install.java

private static void installPublisherKeyGen(EntityManager em, TModel apiTModel, UddiEntityPublisher publisher,
        String nodeId) throws DispositionReportFaultMessage {

    org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel();
    MappingApiToModel.mapTModel(apiTModel, modelTModel);

    modelTModel.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    modelTModel.setCreated(now);/*from w w w  . ja va 2  s  .c  o m*/
    modelTModel.setModified(now);
    modelTModel.setModifiedIncludingChildren(now);
    modelTModel.setNodeId(nodeId);

    em.persist(modelTModel);

}

From source file:com.soen.ebanking.dao.ObjectDao.java

public void addObject(Object entity) {
    EntityManager em = this.getEMF().createEntityManager();
    try {/*  w  w w .  j a v  a  2  s. c o m*/
        em.getTransaction().begin();
        em.persist(entity);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}