Example usage for org.hibernate SessionFactory getCurrentSession

List of usage examples for org.hibernate SessionFactory getCurrentSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory getCurrentSession.

Prototype

Session getCurrentSession() throws HibernateException;

Source Link

Document

Obtains the current session.

Usage

From source file:com.algoTrader.util.HibernateUtil.java

License:Open Source License

public static Object merge(SessionFactory sessionFactory, Object target) {

    Session session = sessionFactory.getCurrentSession();

    return session.merge(target);
}

From source file:com.autobizlogic.abl.logic.dynamic.DatabaseClassManager.java

License:Open Source License

private boolean checkForUpdateHibernate() {
    try {/*from   www  . j a va  2 s.c om*/
        SessionFactory sessFact = cfg.buildSessionFactory();
        Session session = sessFact.getCurrentSession();
        Transaction tx = session.beginTransaction();

        Query query = session.createQuery("from Project where name = :name").setString("name", projectName);
        Project project = (Project) query.uniqueResult();

        LogicFileLog fileLog = loadClassesFromProject(project);
        if (fileLog == null) {
            tx.commit();
            return false;
        }
        session.save(fileLog);

        tx.commit();
        return true;
    } catch (Exception ex) {
        log.error("Unable to check for logic update", ex);
        return false;
    }
}

From source file:com.autobizlogic.abl.logic.dynamic.Deployer.java

License:Open Source License

/**
 * Deploy a jar into a database for use by DatabaseClassManager.
 * @param props Should contain the required parameters:
 * <ul>/*from  w  ww  . j a v a2 s .c o m*/
 * <li>either HIB_CFG_FILE (Hibernate config file path as a string) or 
 * HIB_CFG as a Hibernate Configuration object
 * <li>PROJECT_NAME: the name of the project to deploy to (will be created if it does not exist)
 * <li>JAR_FILE_NAME: the path of the jar file to deploy, as a String
 * <li>EFFECTIVE_DATE: the date/time at which the new logic classes should take effect, 
 * as a java.util.Date (optional)
 * </ul>
 * @return Null if everything went OK, otherwise a reason for the failure
 */
public static String deploy(Properties props) {

    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
    Logger.getLogger("org.hibernate").setLevel(Level.WARN);
    Logger.getLogger("org.hibernate.tool.hbm2ddl").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.transaction").setLevel(Level.DEBUG);

    Configuration config;
    if (props.get(HIB_CFG) == null) {
        config = new Configuration();
        File cfgFile = new File((String) props.get(HIB_CFG_FILE));
        config.configure(cfgFile);
    } else
        config = (Configuration) props.get(HIB_CFG);

    if (config.getClassMapping(Project.class.getName()) == null) {
        config.addAnnotatedClass(Project.class);
        config.addAnnotatedClass(LogicFile.class);
        config.addAnnotatedClass(LogicFileLog.class);
    }

    SessionFactory sessFact = config.buildSessionFactory();
    Session session = sessFact.getCurrentSession();
    Transaction tx = session.beginTransaction();

    Query query = session.createQuery("from Project where name = :name").setString("name",
            (String) props.get(PROJECT_NAME));
    Project project = (Project) query.uniqueResult();
    if (project == null) {
        project = new Project();
        project.setName((String) props.get(PROJECT_NAME));
        session.save(project);
    }

    LogicFile logicFile = new LogicFile();
    String fileName = (String) props.get(JAR_FILE_NAME);
    String shortFileName = fileName;
    if (fileName.length() > 300)
        shortFileName = fileName.substring(0, 300);
    logicFile.setName(shortFileName);
    logicFile.setCreationDate(new Timestamp(System.currentTimeMillis()));
    File jarFile = new File((String) props.get(JAR_FILE_NAME));
    try {
        FileInputStream inStr = new FileInputStream(fileName);
        Blob blob = session.getLobHelper().createBlob(inStr, jarFile.length());
        logicFile.setContent(blob);
    } catch (Exception ex) {
        throw new RuntimeException("Error while storing jar file into database", ex);
    }
    Date effDate = (Date) props.get(EFFECTIVE_DATE);
    logicFile.setEffectiveDate(new Timestamp(effDate.getTime()));
    logicFile.setProject(project);
    session.save(logicFile);

    tx.commit();
    sessFact.close();

    return null;
}

From source file:com.autobizlogic.abl.rule.CountRule.java

License:Open Source License

/**
 * Mechanism to initialize count attribute, e.g., from Domain Object getter.
 * /*ww  w  . jav  a  2 s  .com*/
 * @param aParentDomainObject Domain Object containing the sum
 * @param anAttributeName name of count attribute
 * @param aSessionFactory non EE may require global static, EE can use 
 * sf = (SessionFactory)new InitialContext().lookup("MySessionFactory")
 * @return
 */
public Integer getCountValue(PersistentBean aParentDomainObject, String anAttributeName,
        SessionFactory aSessionFactory) {

    CountRule countRule = null;
    Session session = aSessionFactory.getCurrentSession(); //   aContext.getSession();
    Transaction transaction = session.getTransaction();
    LogicTransactionContext context = LogicTransactionManager
            .getCurrentLogicTransactionContextForTransaction(transaction, session);
    Set<MetaRole> childRoles = aParentDomainObject.getMetaEntity().getRolesFromParentToChildren();
    for (MetaRole eachChildRole : childRoles) {
        Set<AbstractAggregateRule> aggregates = logicGroup.findAggregatesForRole(eachChildRole);
        for (AbstractAggregateRule eachAggregate : aggregates) {
            if (eachAggregate.getBeanAttributeName().equalsIgnoreCase(anAttributeName)) {
                countRule = (CountRule) eachAggregate;
                break;
            }
        }
        if (countRule != null)
            break;
    }
    if (countRule == null)
        throw new LogicException("No Sum definition found for " + anAttributeName);

    return countRule.computeCountInMemory(aParentDomainObject, context);
}

From source file:com.baomidou.hibernateplus.utils.HibernateUtils.java

License:Open Source License

/**
 * ?Session/*  w w  w.  ja  v  a 2  s.com*/
 *
 * @param factory
 * @param isCurrent
 *            ??session
 * @return
 */
public static Session getSession(SessionFactory factory, Boolean isCurrent) {
    return isCurrent ? factory.getCurrentSession() : factory.openSession();
}

From source file:com.bloatit.data.SessionManager.java

License:Open Source License

/**
 * Builds the session factory; Update the lucene index.
 * /*  w w w .  j  a  va 2s.  c o  m*/
 * @return the session factory
 */
private static SessionFactory buildSessionFactory() {
    try {
        final Configuration configuration = createConfiguration().setProperty("hibernate.hbm2ddl.auto",
                "validate");
        final SessionFactory sessionFactory = configuration.buildSessionFactory();

        if (System.getProperty("lucene") == null || System.getProperty("lucene").equals("1")) {
            Search.getFullTextSession(sessionFactory.getCurrentSession()).createIndexer(DaoFeature.class)
                    .startAndWait();
        }

        return sessionFactory;
    } catch (final Exception ex) {
        // Make sure you log the exception, as it might be swallowed
        Log.data().fatal("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.creative.dao.repository.TestUtil.java

License:Apache License

public static void mockCurrentSession(SessionFactory sessionFactory, Session session) {
    when(sessionFactory.getCurrentSession()).thenReturn(session);
}

From source file:com.dreamwork.service.SenderService.java

public void monitoring() throws InterruptedException {
    Thread.sleep(60000L);/*from   w w  w. j ava  2  s. c  om*/
    SessionFactory factory = service.getFactory();
    Session session = factory.getCurrentSession();
    session.beginTransaction();
    List result = session.createQuery("from FutureMail").list();
    for (FutureMail mail : (List<FutureMail>) result) {

        boolean sameDay = DateUtils.isSameDay(new Date(), mail.getWhen());
        if (sameDay) {
            Thread ts = new Thread(new Sender(mail));
            ts.start();
            if (mail.isIsSend()) {
                session.save(mail);
            }

        }
    }
    session.getTransaction().commit();
    session.close();
}

From source file:com.farmafene.aurius.dao.DiccionarioFactoryImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w  ww  .j av  a 2s . co m*/
 * 
 * @see com.farmafene.aurius.core.IDiccionarioFactory#getServicio(java.lang.String)
 */
public Servicio getServicio(String id) throws IllegalArgumentException {

    if (logger.isDebugEnabled()) {
        logger.debug("getServicio(" + id + ")");
    }
    String grupo = FormatUtil.getAplicacionFromIdServicio(id);
    BigDecimal svr_id = new BigDecimal(FormatUtil.getOperacionFromIdServicio(id));

    Session sess = null;
    ServicioSvr svr = null;
    SessionFactory sf = DiccionarioSessionFactory.getSessionFactory();
    sess = sf.getCurrentSession();
    Query q = sess.createQuery("select s from ServicioSvr s,ServicioDesc d where " + "s.id.grupo = d.id.grupo"
            + " and s.id.id = d.id.id" + " and s.id.version = d.version"
            + " and d.id.grupo=:grupo and d.id.id=:id");
    q.setString("grupo", grupo);
    q.setBigDecimal("id", svr_id);
    if (logger.isDebugEnabled()) {
        logger.debug("getServicio(): Begin Query");
    }
    svr = (ServicioSvr) q.uniqueResult();
    if (svr != null) {
        svr.getDescripcion().getRoles();
        if (logger.isDebugEnabled()) {
            logger.debug("getServicio(): End Query");
        }
    }
    return getServicioFromServicioSvr(svr);

}

From source file:com.farmafene.aurius.dao.DiccionarioFactoryImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from  ww  w. ja  v a2 s.  c  om*/
 * 
 * @see com.farmafene.aurius.core.IDiccionarioFactory#getServicio(java.lang.String,
 *      java.lang.String)
 */
public Servicio getServicio(String id, String version) throws IllegalArgumentException {
    if (logger.isDebugEnabled()) {
        logger.debug("getServicio(" + id + ", " + version + ")");
    }
    String grupo = FormatUtil.getAplicacionFromIdServicio(id);
    BigDecimal svr_id = new BigDecimal(FormatUtil.getOperacionFromIdServicio(id));
    BigDecimal v = new BigDecimal(FormatUtil.getNormalizedVersionOperacion(version));

    Session sess = null;
    ServicioSvr svr = null;
    SessionFactory sf = DiccionarioSessionFactory.getSessionFactory();
    sess = sf.getCurrentSession();
    ServicioSvrKey key = new ServicioSvrKey();
    key.setGrupo(grupo);
    key.setId(svr_id);
    key.setVersion(v);
    svr = (ServicioSvr) sess.get(ServicioSvr.class, key);
    svr.getDescripcion().getRoles();
    return getServicioFromServicioSvr(svr);
}