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:org.jtalks.jcommune.model.dao.hibernate.BaseTest.java

License:Open Source License

/**
 * Cleans database table from all records.
 * @param entity instance of {@link Persistent} interface
 * @param sessionFactory Hibernate Session Factory instance
 *///from  www.  ja  va2 s.com
protected void clearDbTable(Persistent entity, SessionFactory sessionFactory) {
    Query query = sessionFactory.getCurrentSession().createQuery("delete " + entity.getClass().getSimpleName());
    query.executeUpdate();
}

From source file:org.libreplan.web.scenarios.ScenarioModelTest.java

License:Open Source License

public static Order givenStoredOrderInScenario(Scenario scenario, IConfigurationDAO configurationDAO,
        IOrderDAO orderDAO, SessionFactory sessionFactory) {
    Order order = Order.create();// w  w w.  j av  a 2  s  . c  o m
    order.setCode(UUID.randomUUID().toString());
    order.setName(randomize("order-name"));
    order.setInitDate(new Date());
    order.setCalendar(configurationDAO.getConfiguration().getDefaultCalendar());

    OrderVersion orderVersion = scenario.addOrder(order);
    order.setVersionForScenario(scenario, orderVersion);
    order.useSchedulingDataFor(orderVersion);
    OrderLine orderLine = OrderLine.createOrderLineWithUnfixedPercentage(1000);
    order.add(orderLine);
    orderLine.setCode(UUID.randomUUID().toString());
    orderLine.setName(randomize("order-line-name"));
    orderDAO.save(order);
    orderDAO.flush();
    sessionFactory.getCurrentSession().evict(order);
    order.dontPoseAsTransientObjectAnymore();

    return order;
}

From source file:org.libreplan.web.scenarios.ScenarioModelTest.java

License:Open Source License

public static Scenario givenStoredScenario(Scenario predecessor, IScenarioDAO scenarioDAO,
        SessionFactory sessionFactory) {
    Scenario scenario = predecessor.newDerivedScenario();
    scenario.setName("scenario-name-" + UUID.randomUUID());

    scenarioDAO.save(scenario);//from w  w  w.j  a v  a2 s. c o  m
    scenarioDAO.flush();
    sessionFactory.getCurrentSession().evict(scenario);
    scenario.dontPoseAsTransientObjectAnymore();

    return scenario;
}

From source file:org.obiba.opal.core.upgrade.v2_0_x.database.FixAttributeJoinTableUpgradeStep.java

License:Open Source License

@SuppressWarnings("unchecked")
private void touchValueTablesTimestamps(final Database database) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override// w  w  w.  j a  va 2s . co  m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            SessionFactory sessionFactory = databaseRegistry.getSessionFactory(database.getName(), null);
            Session currentSession = sessionFactory.getCurrentSession();
            for (ValueTableState table : (List<ValueTableState>) currentSession
                    .createCriteria(ValueTableState.class).list()) {
                log.debug("Touch {} last update", table.getName());
                currentSession.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_FORCE_INCREMENT))
                        .lock(table);
            }
        }
    });
}

From source file:org.openmrs.api.db.hibernate.HibernatePersonDAO.java

License:Mozilla Public License

/**
 * Used by deletePerson, deletePatient, and deleteUser to remove all properties of a person
 * before deleting them.//w w w.  j  a  v a 2s.co  m
 * 
 * @param sessionFactory the session factory from which to pull the current session
 * @param person the person to delete
 */
public static void deletePersonAndAttributes(SessionFactory sessionFactory, Person person) {
    // delete properties and fields so hibernate can't complain
    for (PersonAddress address : person.getAddresses()) {
        if (address.getDateCreated() == null) {
            sessionFactory.getCurrentSession().evict(address);
        } else {
            sessionFactory.getCurrentSession().delete(address);
        }
    }
    person.setAddresses(null);

    for (PersonAttribute attribute : person.getAttributes()) {
        if (attribute.getDateCreated() == null) {
            sessionFactory.getCurrentSession().evict(attribute);
        } else {
            sessionFactory.getCurrentSession().delete(attribute);
        }
    }
    person.setAttributes(null);

    for (PersonName name : person.getNames()) {
        if (name.getDateCreated() == null) {
            sessionFactory.getCurrentSession().evict(name);
        } else {
            sessionFactory.getCurrentSession().delete(name);
        }
    }
    person.setNames(null);

    // finally, just tell hibernate to delete our object
    sessionFactory.getCurrentSession().delete(person);
}

From source file:org.openmrs.api.db.hibernate.HibernateUtil.java

License:Mozilla Public License

/**
 * @see HibernateUtil#escapeSqlWildcards(String, Connection)
 */// w  w  w .j a va2 s .c  om
public static String escapeSqlWildcards(final String oldString, SessionFactory sessionFactory) {
    return sessionFactory.getCurrentSession().doReturningWork(new ReturningWork<String>() {

        @Override
        public String execute(Connection connection) throws SQLException {
            return escapeSqlWildcards(oldString, connection);
        }
    });

}

From source file:org.openmrs.api.db.hibernate.PatientSearchCriteriaTest.java

License:Mozilla Public License

@Before
public void setUp() {
    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Patient.class);

    patientSearchCriteria = new PatientSearchCriteria(sessionFactory, criteria);
    globalPropertiesTestHelper = new GlobalPropertiesTestHelper(Context.getAdministrationService());
}

From source file:org.openmrs.BaseOpenmrsObjectTest.java

License:Mozilla Public License

/**
 * @see BaseOpenmrsObject#equals(Object)
 *//*from   w w w .  ja  va  2s.co  m*/
@Test
public void equals_shouldReturnfalseIfHibernateProxyOfOneThingIsComparedtoHibernateProxyofSomething() {
    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.getCurrentSession();
    Assert.assertFalse((session.load(Patient.class, 2)).equals((session.load(Concept.class, 11))));
}

From source file:org.openmrs.BaseOpenmrsObjectTest.java

License:Mozilla Public License

/**
 * @see BaseOpenmrsObject#equals(Object)
 *//*w  ww .  j  ava 2s.c om*/
@Test
public void equals_shouldReturnFalseIfHibernateProxyOfOneThingIsComparedtoNonHibernateProxyofSomething() {
    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.getCurrentSession();

    //NonHibernate managed class declaration
    class TestClass extends BaseOpenmrsObject {
        private Integer id;

        TestClass() {
        }

        @Override
        public Integer getId() {
            return id;
        }

        @Override
        public void setId(Integer id) {
            this.id = id;
        }

        @Override
        public int hashCode() {
            if (getUuid() == null) {
                return super.hashCode();
            }
            return getUuid().hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof TestClass)) {
                return false;
            }
            TestClass other = (TestClass) obj;
            if (getUuid() == null) {
                return false;
            }
            return getUuid().equals(other.getUuid());
        }

        @Override
        public String toString() {
            return new org.apache.commons.lang3.builder.ToStringBuilder(this,
                    org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE)
                            .append("hashCode", Integer.toHexString(hashCode())).append("uuid", getUuid())
                            .build();
        }
    }

    Patient patient = (Patient) session.get(Patient.class, 2);
    String uid = patient.getUuid();

    //NonHibernate managed class Instantiation
    TestClass obj = new TestClass();
    obj.setUuid(uid);

    Assert.assertFalse(obj.equals((session.load(Patient.class, 2))));
    Assert.assertFalse((session.load(Patient.class, 2)).equals(obj));
}

From source file:org.openmrs.BaseOpenmrsObjectTest.java

License:Mozilla Public License

/**
 * @see BaseOpenmrsObject#equals(Object)
 *//*w  w w. j a  va2 s. c  om*/
@Test
public void equals_shouldReturnTrueIfHibernateProxyOfOneObjectComparedToNonHibernateProxyOfTheSameObject() {
    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.getCurrentSession();

    Patient patient = (Patient) session.get(Patient.class, 2);
    Patient patientproxyobject = (Patient) session.load(Patient.class, 2);

    Assert.assertTrue(patient.equals(patientproxyobject));
}