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:es.us.isa.ideas.utilities.PopulateDatabase.java

public static void main(String[] args) {

    ApplicationContext ctx;/*w  ww .  j av a  2 s  .c o m*/
    EntityManagerFactory emf;
    EntityManager em;
    EntityTransaction et;

    ctx = new ClassPathXmlApplicationContext("utilities/PopulateDatabase.xml");

    emf = Persistence.createEntityManagerFactory("persistenceUnit");
    em = emf.createEntityManager();
    et = em.getTransaction();

    et.begin();
    try {
        for (Entry<String, Object> entry : ctx.getBeansWithAnnotation(Entity.class).entrySet()) {
            em.persist(entry.getValue());
            System.out.println(String.format("Persisting (%s, %s@%d)", entry.getKey(),
                    entry.getValue().getClass().getName(), entry.getValue().hashCode()));
        }
        et.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        et.rollback();
        oops.printStackTrace();
    } finally {
        if (em.isOpen())
            em.close();
        if (emf.isOpen())
            emf.close();
        ((ClassPathXmlApplicationContext) ctx).close();
    }
}

From source file:pt.souplesse.spark.Server.java

public static void main(String[] args) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("guestbook");
    EntityManager manager = factory.createEntityManager();
    JinqJPAStreamProvider streams = new JinqJPAStreamProvider(factory);
    get("/messages", (req, rsp) -> {
        rsp.type("application/json");
        return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList()));
    });/*from w w w .  j  a  v  a  2s  . com*/
    post("/messages", (req, rsp) -> {
        try {
            Message msg = gson.fromJson(req.body(), Message.class);
            if (StringUtils.isBlank(msg.getMessage()) || StringUtils.isBlank(msg.getName())) {
                halt(400);
            }
            manager.getTransaction().begin();
            manager.persist(msg);
            manager.getTransaction().commit();
        } catch (JsonSyntaxException e) {
            halt(400);
        }
        rsp.type("application/json");
        return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList()));
    });
    get("/comments", (req, rsp) -> {
        rsp.type("application/json");
        Map<String, List<Body>> body = new HashMap<>();
        try (CloseableHttpClient client = create().build()) {
            String url = String.format("https://api.github.com/repos/%s/events", req.queryMap("repo").value());
            log.info(url);
            body = client.execute(new HttpGet(url), r -> {
                List<Map<String, Object>> list = gson.fromJson(EntityUtils.toString(r.getEntity()), List.class);
                Map<String, List<Body>> result = new HashMap<>();
                list.stream().filter(m -> m.getOrDefault("type", "").equals("IssueCommentEvent"))
                        .map(m -> new Body(((Map<String, String>) m.get("actor")).get("login"),
                                ((Map<String, Map<String, String>>) m.get("payload")).get("comment")
                                        .get("body")))
                        .forEach(b -> result.compute(b.getLogin(), (k, v) -> v == null ? new ArrayList<>()
                                : Lists.asList(b, v.toArray(new Body[v.size()]))));
                return result;
            });
        } catch (IOException e) {
            log.error(null, e);
            halt(400, e.getMessage());
        }
        return gson.toJson(body);
    });
}

From source file:utilities.PopulateDatabase.java

public static void main(String[] args) throws Throwable {
    ApplicationContext applicationContext;
    EntityManagerFactory entityManagerFactory;
    EntityManager entityManager;
    EntityTransaction entityTransaction;

    applicationContext = new ClassPathXmlApplicationContext("classpath:PopulateDatabase.xml");

    entityManagerFactory = Persistence.createEntityManagerFactory(PersistenceUnit);
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();

    initialise(entityManagerFactory, entityManager);

    entityTransaction.begin();/*from   w  ww .  ja  va2s  .  co m*/
    try {
        for (Entry<String, Object> entry : applicationContext.getBeansWithAnnotation(Entity.class).entrySet()) {
            String beanName;
            DomainEntity entity;

            beanName = entry.getKey();
            entity = (DomainEntity) entry.getValue();
            entityManager.persist(entity);
            System.out.println(String.format("Persisting (%s, %s, %d)", beanName, entity.getClass().getName(),
                    entity.getId()));
        }
        entityTransaction.commit();
    } catch (Exception oops) {
        oops.printStackTrace();
        entityTransaction.rollback();
    } finally {
        if (entityManager.isOpen())
            entityManager.close();
        if (entityManagerFactory.isOpen())
            entityManagerFactory.close();
    }
}

From source file:org.mitre.util.jpa.JpaUtil.java

public static <T, I> T saveOrUpdate(I id, EntityManager entityManager, T entity) {
    if (id == null) {
        entityManager.persist(entity);
        entityManager.flush();//from www . ja v  a 2s .  c o m
        return entity;
    } else {
        T tmp = entityManager.merge(entity);
        entityManager.flush();
        return tmp;
    }
}

From source file:GestoreAccountLocale.GestoreAccountLocale.java

private static void memorizzaAccount(Account account) {
    EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("ClientMDBPU");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//from   w  w  w  .  java2s  . com
    try {
        em.persist(account);
        em.getTransaction().commit();
    } catch (Exception e) {
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
}

From source file:com.impetus.kvapps.runner.ExecutorService.java

/**
 * @param user//  w  w  w  .j a v  a 2 s. c om
 */
private static void persist(User user, final EntityManager em) {
    em.persist(user);
}

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.LastHarvested.java

/**
 * Save or update a timestamp.//from   w w  w  .j a v a  2  s  . c  o m
 */
public static void update(PersistenceEnv penv, final LastHarvested entity) {
    penv.tx(new Function<EntityManager, Void>() {
        public Void apply(EntityManager em) {
            LastHarvested existing = em.find(LastHarvested.class, entity.getUrl());
            if (existing != null) {
                em.persist(em.merge(entity));
            } else {
                em.persist(entity);
            }
            return null;
        }
    });
}

From source file:org.opencastproject.oaipmh.harvester.LastHarvested.java

/**
 * Save or update a timestamp.//from   w w  w  .  java 2 s.com
 */
public static void update(PersistenceEnv penv, final LastHarvested entity) {
    penv.tx(new Function<EntityManager, Void>() {
        @Override
        public Void apply(EntityManager em) {
            LastHarvested existing = em.find(LastHarvested.class, entity.getUrl());
            if (existing != null) {
                em.persist(em.merge(entity));
            } else {
                em.persist(entity);
            }
            return null;
        }
    });
}

From source file:ch.puzzle.itc.mobiliar.test.PersistingEntityBuilder.java

public static ResourceTypeEntity buildResourceType(EntityManager em, String name) {
    ResourceTypeEntity type = new ResourceTypeEntity();
    type.setName(name);//from   ww w.j a  v a  2s . c  o m
    em.persist(type);
    return type;
}

From source file:com.autentia.common.util.ejb.EntityManagerUtils.java

/**
 * Saves an entity in the persistence layer. If the entity doesn't exist, this method inserts the entity. If the
 * entity already exists in the persistence layer, this method updates the entity.
 * <p>//w  w  w. j  a va  2  s  . com
 * Usage example: <code>save(em, company, company.getId())</code>
 * 
 * @param em the {@link EntityManager} where the inserto or update will be executed.
 * @param entity the entity to save.
 * @param id the primary key of the entity.
 */
public static void save(EntityManager em, Object entity, Object id) {
    if (id == null) {
        em.persist(entity);
    } else if (!em.contains(entity)) {
        em.merge(entity);
    }
}