Example usage for org.hibernate Session persist

List of usage examples for org.hibernate Session persist

Introduction

In this page you can find the example usage for org.hibernate Session persist.

Prototype

void persist(Object object);

Source Link

Document

Make a transient instance persistent.

Usage

From source file:org.exoplatform.common.dao.hibernate.HibernateJpaRepository.java

License:Open Source License

/**
 * <p>/*from  www  . j av a2  s .co m*/
 * Make a transient instance persistent and add it to the datastore. This
 * operation cascades to associated instances if the association is mapped
 * with cascade="persist". Throws an error if the entity already exists.
 * 
 * <p>
 * This is different from <code>save()</code> in that it does not guarantee
 * that the object will be assigned an identifier immediately. With
 * <code>save()</code> a call is made to the datastore immediately if the id
 * is generated by the datastore so that the id can be determined. With
 * <code>persist</code> this call may not occur until flush time.
 */
public void _persistEntities(Object... entities) {
    Session session = openSession();
    try {
        for (Object entity : entities) {
            session.persist(entity);
        }
        session.flush();
        session.clear();
    } finally {
        session.close();
    }
}

From source file:org.firstopen.singularity.system.dao.ReaderEventDAOImpl.java

License:Apache License

public void persist(ReaderEvent readerEvent) throws InfrastructureException {

    Session session = null;
    hibernateUtil.beginTransaction();/*  www .  ja v  a 2  s  . c o  m*/
    session = hibernateUtil.getSession();
    session.persist(readerEvent);

}

From source file:org.gatein.wsrp.consumer.registry.hibernate.HibernateConsumerRegistry.java

License:Open Source License

public void save(ProducerInfo info, String messageOnError) {
    try {//from w  w  w .j a  v  a 2 s.c o  m
        Session session = sessionFactory.getCurrentSession();
        session.persist(info);
    } catch (HibernateException e) {
        throw new ConsumerException(messageOnError, e);
    }
}

From source file:org.genedb.db.loading.FastaLoader.java

License:Open Source License

/**
 * This method is called once for each FASTA file.
 *
 * @param fileId the identifier of the file
 * @param records the records the file contains
 *//*from   ww w. jav  a2 s . co m*/
public void load(String fileId, Iterable<FastaRecord> records) {
    logger.debug(String.format("beginFastaFile(%s)", fileId));

    Session session = SessionFactoryUtils.doGetSession(sessionFactory, false);
    StringBuilder concatenatedSequences = new StringBuilder();

    Feature existingTopLevelFeature = (Feature) session.createCriteria(Feature.class)
            .add(Restrictions.eq("organism", organism)).add(Restrictions.eq("uniqueName", fileId))
            .uniqueResult();

    if (existingTopLevelFeature != null) {
        switch (overwriteExisting) {
        case YES:
            existingTopLevelFeature.delete();
            break;
        case NO:
            logger.error(String.format("The organism '%s' already has feature '%s'", organism.getCommonName(),
                    fileId));
            return;
        }
    }
    TopLevelFeature topLevelFeature = null;
    if (topLevelFeatureClass != null) {
        topLevelFeature = TopLevelFeature.make(topLevelFeatureClass, fileId, organism);
        topLevelFeature.markAsTopLevelFeature();
        session.persist(topLevelFeature);
    }

    int start = 0;
    for (FastaRecord record : records) {
        String id = record.getId();
        String sequence = record.getSequence();

        if (topLevelFeature != null) {
            concatenatedSequences.append(sequence);
        }

        int end = start + sequence.length();
        TopLevelFeature entry = TopLevelFeature.make(entryClass, id, organism);
        entry.setResidues(sequence);
        if (topLevelFeature == null) {
            entry.markAsTopLevelFeature();
        } else {
            topLevelFeature.addLocatedChild(entry, start, end);
        }
        session.persist(entry);
        start = end;
    }

    if (topLevelFeature != null) {
        topLevelFeature.setResidues(concatenatedSequences.toString());
    }
}

From source file:org.granite.test.tide.spring.service.Hibernate3JobService.java

License:Open Source License

public Object[] apply(Long jobId, Long userId) {
    Session session = getSession();

    Job job = (Job) session.load(Job.class, jobId);
    User user = (User) session.load(User.class, userId);

    JobApplication application = new JobApplication();
    application.initUid();/*  www  .  j av a  2 s.co  m*/
    application.setDate(new Date(new java.util.Date().getTime()));
    application.setJob(job);
    application.setUser(user);
    session.persist(application);

    job.getApplications().add(application);
    user.getApplications().add(application);

    return new Object[] { job, user, application };
}

From source file:org.harms.orm.upgrade.Jpa21TestDao.java

License:Open Source License

public Jpa21TestEntity save(Jpa21TestEntity entity) {
    Session session = entityManager.unwrap(Session.class);
    session.persist(entity);
    session.flush();//from w w  w .ja  v a2s  .c  o m
    session.clear();

    session.flush();
    session.clear();

    // EntityManager methods exposed through Session only as of 5.2
    return session.find(Jpa21TestEntity.class, entity.getId());
}

From source file:org.infinispan.test.hibernate.cache.commons.stress.PutFromLoadStressTestCase.java

License:LGPL

private void store() throws Exception {
    for (int i = 0; i < NUM_INSTANCES; i++) {
        final Age age = new Age();
        age.setAge(i);/*from   w  w  w .j  ava  2 s. c om*/
        withTx(tm, new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                Session s = sessionFactory.openSession();
                s.getTransaction().begin();
                s.persist(age);
                s.getTransaction().commit();
                s.close();
                return null;
            }
        });
    }
}

From source file:org.infinispan.test.hibernate.cache.commons.stress.SecondLevelCacheStressTestCase.java

License:LGPL

Operation insertOperation() {
    return new Operation("INSERT") {
        @Override/*from  w  w  w.j a  va 2 s . c om*/
        boolean call(final int run) throws Exception {
            return captureThrowables(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return withTx(tm, new Callable<Boolean>() {
                        @Override
                        public Boolean call() throws Exception {
                            Session s = sessionFactory.openSession();
                            s.getTransaction().begin();

                            String name = "Zamarreo-" + run;
                            Family family = new Family(name);
                            s.persist(family);

                            s.getTransaction().commit();
                            s.close();
                            return true;
                        }
                    });
                }
            });
        }
    };
}

From source file:org.infinispan.test.hibernate.cache.commons.tm.JBossStandaloneJtaExampleTest.java

License:LGPL

@Test
public void testPersistAndLoadUnderJta() throws Exception {
    Item item;/* www.ja va 2 s.  c o m*/
    SessionFactory sessionFactory = buildSessionFactory();
    try {
        UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertEquals(TransactionStatus.ACTIVE, session.getTransaction().getStatus());
            item = new Item("anItem", "An item owned by someone");
            session.persist(item);
            // IMO the flush should not be necessary, but session.close() does not flush
            // and the item is not persisted.
            session.flush();
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }

        ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertEquals(TransactionStatus.ACTIVE, session.getTransaction().getStatus());
            Item found = (Item) session.load(Item.class, item.getId());
            Statistics stats = session.getSessionFactory().getStatistics();
            log.info(stats.toString());
            assertEquals(item.getDescription(), found.getDescription());
            assertEquals(0, stats.getSecondLevelCacheMissCount());
            assertEquals(1, stats.getSecondLevelCacheHitCount());
            session.delete(found);
            // IMO the flush should not be necessary, but session.close() does not flush
            // and the item is not deleted.
            session.flush();
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }

        ut = (UserTransaction) ctx.lookup("UserTransaction");
        ut.begin();
        try {
            Session session = sessionFactory.openSession();
            assertEquals(TransactionStatus.ACTIVE, session.getTransaction().getStatus());
            assertNull(session.get(Item.class, item.getId()));
            session.close();
        } catch (Exception e) {
            ut.setRollbackOnly();
            throw e;
        } finally {
            if (ut.getStatus() == Status.STATUS_ACTIVE)
                ut.commit();
            else
                ut.rollback();
        }
    } finally {
        if (sessionFactory != null)
            sessionFactory.close();
    }

}

From source file:org.infinispan.tutorial.secondlc.wildfly.local.service.MemberRegistration.java

License:Apache License

public void register(Member member) throws Exception {
    log.info("Registering " + member.getName());
    // em.persist(member);

    // using Hibernate session(Native API) and JPA entitymanager
    Session session = (Session) em.getDelegate();
    session.persist(member);
    memberEventSrc.fire(member);/*from w  w w.  j  a  v  a 2 s  .  c o  m*/
}