Example usage for org.hibernate Session flush

List of usage examples for org.hibernate Session flush

Introduction

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

Prototype

void flush() throws HibernateException;

Source Link

Document

Force this session to flush.

Usage

From source file:ca.myewb.model.PostModel.java

License:Open Source License

public static PostModel newPost(UserModel currentUser, GroupModel targetGroup, String subject, String intro,
        String body, String unsplitTags, boolean whiteboard) {
    Session hibernateSession = HibernateUtil.currentSession();
    PostModel p = new PostModel();
    hibernateSession.save(p);//w  w  w. j  ava2  s  .  c  o m
    AjaxServlet.invalidateFrontPageCache(targetGroup.getId());

    p.setSubject(subject);
    p.setIntro(intro);

    if (!body.trim().equals("")) {
        p.setBody(body);
    }

    targetGroup.addPost(p);

    for (String tag : TagLogic.extractTagNames(unsplitTags)) {
        p.addTag(TagModel.getOrCreateTag(tag));
    }

    currentUser.addPost(p);

    hibernateSession.flush();

    if (whiteboard) {
        p.setWhiteboard(WhiteboardModel.newWhiteboard(null, p, null));
    }
    Helpers.currentDailyStats().logPost();

    p.setSearchable(SearchableModel.newSearchable(p, null, null));

    return p;
}

From source file:ca.myewb.model.PostModel.java

License:Open Source License

public PostModel reply(UserModel currentUser, String body, String tags) {
    if (!hasActiveWhiteboard()) {
        Session hibernateSession = HibernateUtil.currentSession();
        PostModel p = new PostModel();
        hibernateSession.save(p);//from   w w w . j  a v a 2s. c  o  m
        AjaxServlet.invalidateFrontPageCache(getGroup().getId());

        p.setBody(body);
        addReply(p); //sets group on reply

        Logger.getLogger(this.getClass())
                .info("Post " + this.getId() + " has " + this.getReplies().size() + " replies.");

        if (this.getReplies().size() == Post.RepliesToFeature) {
            this.feature();
        }

        if (this.isFeatured()) {
            p.feature();
        }

        for (String tag : TagLogic.extractTagNames(tags)) {
            addTag(TagModel.getOrCreateTag(tag));
        }

        currentUser.addPost(p);

        setLastReply(new Date());

        hibernateSession.flush();
        Helpers.currentDailyStats().logReply();

        p.setSearchable(SearchableModel.newSearchable(p, null, null));

        return p;
    } else {
        Logger.getLogger(this.getClass()).debug("Tried to reply to a post that has a whiteboard.");
        return null;
    }

}

From source file:ca.myewb.model.UserModel.java

License:Open Source License

public static UserModel createGuestUser() throws Exception {
    Session session = HibernateUtil.currentSession();
    UserModel guest = new UserModel();
    guest.setUsername("guest");
    session.save(guest);// ww  w.  j a va  2s.co  m
    guest.addGroup(Helpers.getGroup("Org"), 'm');
    guest.addGroup(Helpers.getGroup("Guest"), 'm');
    guest.addGroup(Helpers.getGroup("NoChapter"), 'm');
    session.flush();
    return guest;
}

From source file:ca.ualberta.physics.cssdp.catalogue.dao.UrlDataProductDao.java

License:Apache License

public void process(UrlDataProductUpdateMap urlDataProductUpdateMap) {

    if (urlDataProductUpdateMap.getUrls().size() == 0) {
        return;// w  w  w  .  j a  v a 2s .c om
    }

    /*
     * The size of scannedUrlDataProducts should be <= jdbc batch size
     * configured.
     */

    // we have to resort to hibernate directly because JPA does not have
    // scrolling capability
    Session session = emp.get().unwrap(Session.class).getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();

    // "in" clause limit is 2^16 on Postgresql, it might be different on
    // other dbs
    String hqlString = "from UrlDataProduct urldp where urldp.url in (:urls)";

    // the fastest way to scroll through the existing data
    Query q = session.createQuery(hqlString);
    q.setParameterList("urls", urlDataProductUpdateMap.getUrls());
    q.setCacheMode(CacheMode.IGNORE);
    ScrollableResults existingData = q.scroll(ScrollMode.FORWARD_ONLY);

    while (existingData.next()) {

        UrlDataProduct existing = (UrlDataProduct) existingData.get(0);
        UrlDataProduct updated = urlDataProductUpdateMap.get(existing.getUrl());

        if (updated != null) {

            /*
             * Only bother to update the record if it's actually changed.
             * Note that the scan timestamp is ignored in the check because
             * that isn't something the provider changed. A change can also
             * mean the url was deleted, and now it's back.
             */
            if (existing.hasChanged(updated)) {
                // existing.setDataProduct(updated.getDataProduct());
                existing.setUrl(updated.getUrl());
                existing.setStartTimestamp(updated.getStartTimestamp());
                existing.setEndTimestamp(updated.getEndTimestamp());
                existing.setScanTimestamp(updated.getScanTimestamp());
                existing.setDeleted(false);
                urlDataProductUpdateMap.remove(updated.getUrl());
                session.update(existing);
            } else {
                // remove it so it's not duplicated
                urlDataProductUpdateMap.remove(existing.getUrl());
            }

        } else {

            // if we get here it means the existing url has been removed
            // from the server, set "delete" it from the catalogue
            existing.setDeleted(true);
            existing.setScanTimestamp(new LocalDateTime());

        }

    }

    // persist the new url mappings
    for (String newUrl : urlDataProductUpdateMap.getUrls()) {
        UrlDataProduct newUrlDataProduct = urlDataProductUpdateMap.get(newUrl);
        session.save(newUrlDataProduct);
        logger.debug("saved a mapping: " + newUrlDataProduct.getUrl());
    }

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

    tx.commit();
    session.close();

}

From source file:cgt.TesteHibernate.java

/**
 * @param args the command line arguments
 *///from w  w w.j a  v a  2s .  c o  m
public static void main(String[] args) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session sessao = sf.openSession();

    Pessoa pes = new Pessoa();
    Endereco endereco = new Endereco();

    endereco.setBairro("centro");
    endereco.setCep(29725000);
    endereco.setCidade("Marilndia");
    endereco.setRua("Virginia Paganini Tozzi");

    pes.setCpf("12156544727");
    pes.setNome("Artur");
    pes.setEndereco(endereco);
    pes.setTelefone01(000000);
    pes.setTelefone02(111111);

    Transaction ts = sessao.beginTransaction();

    sessao.save(endereco);
    sessao.save(pes);

    ts.commit();
    sessao.flush();
    sessao.close();
}

From source file:ch.algotrader.cache.CacheTest.java

License:Open Source License

@BeforeClass
public static void beforeClass() {

    context = new AnnotationConfigApplicationContext();
    context.getEnvironment().setActiveProfiles("embeddedDataSource", "simulation");

    // register in-memory db
    EmbeddedDatabaseFactory dbFactory = new EmbeddedDatabaseFactory();
    dbFactory.setDatabaseType(EmbeddedDatabaseType.H2);
    dbFactory.setDatabaseName("testdb;MODE=MYSQL;DATABASE_TO_UPPER=FALSE");

    database = dbFactory.getDatabase();/*w  ww.j  ava 2s.c o m*/
    context.getDefaultListableBeanFactory().registerSingleton("dataSource", database);

    EngineManager engineManager = Mockito.mock(EngineManager.class);
    Mockito.when(engineManager.getCurrentEPTime()).thenReturn(new Date());
    Mockito.when(engineManager.getCurrentEPTime()).thenReturn(new Date());
    context.getDefaultListableBeanFactory().registerSingleton("engineManager", engineManager);

    AtomicReference<TransactionService> transactionService = new AtomicReference<>();
    Engine engine = new NoopEngine(StrategyImpl.SERVER);

    context.getDefaultListableBeanFactory().registerSingleton("serverEngine", engine);

    ExternalMarketDataService externalMarketDataService = Mockito.mock(ExternalMarketDataService.class);
    context.getDefaultListableBeanFactory().registerSingleton("externalMarketDataService",
            externalMarketDataService);

    context.getDefaultListableBeanFactory().registerSingleton("historicalDataService",
            new NoopHistoricalDataServiceImpl());

    Mockito.when(externalMarketDataService.getFeedType()).thenReturn(FeedType.IB.name());

    // register Wirings
    context.register(CommonConfigWiring.class, CoreConfigWiring.class, EventDispatchWiring.class,
            EventDispatchPostInitWiring.class, HibernateWiring.class, CacheWiring.class, DaoWiring.class,
            ServiceWiring.class, SimulationWiring.class);

    context.refresh();

    transactionService.set(context.getBean(TransactionService.class));

    cache = context.getBean(CacheManager.class);
    txTemplate = context.getBean(TransactionTemplate.class);

    // create the database
    ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator();
    dbPopulator.addScript(new ClassPathResource("/db/h2/h2.sql"));
    DatabasePopulatorUtils.execute(dbPopulator, database);

    // populate the database
    SessionFactory sessionFactory = context.getBean(SessionFactory.class);
    Session session = sessionFactory.openSession();

    Exchange exchange1 = new ExchangeImpl();
    exchange1.setName("IDEALPRO");
    exchange1.setCode("IDEALPRO");
    exchange1.setTimeZone("US/Eastern");
    session.save(exchange1);

    SecurityFamily family1 = new SecurityFamilyImpl();
    family1.setName("FX");
    family1.setTickSizePattern("0<0.1");
    family1.setCurrency(Currency.USD);
    family1.setExchange(exchange1);
    family1.setTradeable(true);
    family1.setContractSize(1.0);
    securityFamilyId1 = (Long) session.save(family1);

    SecurityFamily family2 = new SecurityFamilyImpl();
    family2.setName("NON_TRADEABLE");
    family2.setTickSizePattern("0<0.1");
    family2.setCurrency(Currency.USD);
    family2.setTradeable(false);
    family2.setContractSize(1.0);
    securityFamilyId2 = (Long) session.save(family2);

    Forex security1 = new ForexImpl();
    security1.setSymbol("EUR.USD");
    security1.setBaseCurrency(Currency.EUR);
    security1.setSecurityFamily(family1);
    securityId1 = (Long) session.save(security1);

    Forex security2 = new ForexImpl();
    security2.setSymbol("GBP.USD");
    security2.setBaseCurrency(Currency.GBP);
    security2.setSecurityFamily(family1);
    security2.setUnderlying(security1);
    securityId2 = (Long) session.save(security2);

    Strategy strategy1 = new StrategyImpl();
    strategy1.setName(STRATEGY_NAME);
    strategyId1 = (Long) session.save(strategy1);

    Position position1 = new PositionImpl();
    position1.setQuantity(222);
    position1.setStrategy(strategy1);
    position1.setSecurity(security2);
    position1.setCost(new BigDecimal(0.0));
    position1.setRealizedPL(new BigDecimal(0.0));

    session.save(position1);

    Property property1 = new PropertyImpl();
    property1.setName(PROPERTY_NAME);
    property1.setDoubleValue(10.0);
    property1.setPropertyHolder(strategy1);
    session.save(property1);
    strategy1.getProps().put(PROPERTY_NAME, property1);

    Account account1 = new AccountImpl();
    account1.setName("TEST");
    account1.setBroker("TEST");
    account1.setOrderServiceType(OrderServiceType.SIMULATION.toString());
    accountId1 = (Long) session.save(account1);

    session.flush();
    session.close();
}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

public void flush() {

    Session currentSession = getCurrentSession();
    currentSession.flush();
}

From source file:ch.icclab.cyclops.persistence.HibernateClient.java

License:Open Source License

/**
 * Let Hibernate store provided object to database
 * @param obj to be stored/* ww  w  .  ja  va 2 s .c o m*/
 * @return updated object
 */
public Object persistObject(Object obj) {

    // first get session
    Session session = obtainSession();

    // start transaction
    session.beginTransaction();

    // persist object
    session.saveOrUpdate(obj);

    // commit it
    session.getTransaction().commit();

    // close connection
    session.flush();
    session.close();

    return obj;
}

From source file:ch.icclab.cyclops.persistence.HibernateClient.java

License:Open Source License

/**
 * Remove object from database/*from  w w  w.  ja  v a  2 s.c  om*/
 * @param obj object to be deleted
 */
public Boolean deleteObject(Object obj) {

    try {
        // get session
        Session session = obtainSession();

        // now delete it
        session.delete(obj);

        // close
        session.flush();
        session.close();

        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:ch.tatool.app.service.impl.ModuleDAO.java

License:Open Source License

/**
 * Deletes a module/* w  ww  . ja  v a  2  s.  c om*/
 * 
 * @param module the module to load
 */
public void deleteModule(final ModuleInfoImpl moduleInfo) {
    getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            // PENDING: can't hibernate figure this out on its own?
            // First delete all trials
            List<?> trialIds = session
                    .createQuery("select id from TrialImpl trial where trial.session.module.id = :id")
                    .setParameter("id", moduleInfo.getId()).list();
            for (Object o : trialIds) {
                TrialImpl trial = new TrialImpl();
                session.load(trial, (Long) o);
                session.delete(trial);
                //session.createQuery("delete TrialImpl trial where trial.id = :id").setParameter("id", o).executeUpdate();
            }
            session.flush();

            // then delete the sessions
            List<?> sessionIds = session
                    .createQuery("select id from ModuleSessionImpl session where session.module.id = :id")
                    .setParameter("id", moduleInfo.getId()).list();
            for (Object o : sessionIds) {
                ModuleSessionImpl s = new ModuleSessionImpl();
                session.load(s, (Long) o);
                session.delete(s);
            }

            // finally delete the module
            // Does not work because for some reason the module properties are not deleted in cascade...
            /*
            Query query = session.createQuery("delete from ModuleImpl module where module-id = :moduleId");
            query.setLong("moduleId", moduleInfo.getId());
            query.executeUpdate();
            */

            // and finally the module itself
            ModuleImpl module = loadModule(moduleInfo);
            session.delete(module);
            return null;
        }
    });
}