Example usage for org.hibernate Session clear

List of usage examples for org.hibernate Session clear

Introduction

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

Prototype

void clear();

Source Link

Document

Completely clear the session.

Usage

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public List<Usuario> getAll() {
    List<Usuario> res = new ArrayList<Usuario>(0);
    org.hibernate.Session currentSession = getSession();
    currentSession.clear();
    res = currentSession.createCriteria(Usuario.class).addOrder(Order.desc("nombreUsuario"))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

    return res;//from  w ww . j  ava  2  s  .c  o  m
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public List<Usuario> getAll(String order, boolean asc) {
    List<Usuario> res = new ArrayList<Usuario>(0);
    org.hibernate.Session currentSession = getSession();
    currentSession.clear();
    if (asc)/*from  w  w w .ja  v a2  s  . c om*/
        res = currentSession.createCriteria(Usuario.class).addOrder(Order.asc("order"))
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
    else
        res = currentSession.createCriteria(Usuario.class).addOrder(Order.desc("order"))
                .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

    return res;
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public boolean alreadyExists(String nombreUsuario) {
    if (nombreUsuario == null)
        return false;
    org.hibernate.Session currentSession = getSession();
    currentSession.clear();

    Integer count = (Integer) currentSession.createCriteria(Usuario.class)
            .add(Restrictions.eq("nombreUsuario", nombreUsuario)).setProjection(Projections.rowCount())
            .uniqueResult();/* w w  w  . j a va2s  .com*/

    return (count != 0);
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@Transactional(readOnly = false, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public boolean saveOrUpdate(Usuario entity) {
    log.trace("saveOrUpdate(" + entity + ")");
    if (entity == null)
        throw new NullPointerException("No se puede guardar un usuario nulo");
    org.hibernate.Session currentSession = getSession();
    currentSession.clear();
    Object e = null;//from   w w  w .  ja  va 2  s .  c o m
    try {
        if (entity.getId() == null || (entity.getId() != null && this.get(entity.getId()) == null)) {
            log.trace("Tenemos que crear un usuario nuevo");
            e = entity;
        } else {
            log.trace("Hacemos update sobre un usuario ya antiguo");
            e = currentSession.merge(entity);
        }
    } catch (Throwable t) {
        log.error("Tiene toda la pinta de que estamos guardando algo ya borrado", t);
    }
    if (e == null) {
        log.debug("Error al mergear");
        throw new NullPointerException("No se puede guardar el usuario, es nulo");
    }
    currentSession.saveOrUpdate(e);
    log.trace("saved");
    return true;
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@Transactional(readOnly = false, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public boolean delete(Usuario entity) {
    if (entity == null)
        throw new NullPointerException("El usuario a borrar es nulo.");

    org.hibernate.Session currentSession = getSession();
    currentSession.clear();
    if (entity.getId() == null)
        return true;

    try {/* w w  w.  jav  a 2 s .  c o  m*/
        entity = this.get(entity.getId());
    } catch (Throwable t) {
        log.error("Tiene toda la pinta de que estamos borrando algo ya borrado.", t);
    }

    if (entity == null)
        return true;

    if (entity.getClientesConectados() != null && entity.getClientesConectados().size() > 0) {
        log.debug("Se intent borrar a un usuario conectado a una estacin fija.");
        return false;
    }

    currentSession
            .createSQLQuery("delete from  usuarios_x_capas_informacion where fk_usuarios=" + entity.getId())
            .executeUpdate();

    this.remove(entity.getId());

    return true;
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public Usuario find(String nombreUsuario) {
    try {//  w w w  . j a v a2  s .  c  om
        org.hibernate.Session currentSession = getSession();
        if (currentSession == null)
            throw new RuntimeException("No tenemos session");
        currentSession.clear();
        Usuario u = (Usuario) currentSession.createCriteria(Usuario.class)
                .add(Restrictions.eq("nombreUsuario", nombreUsuario)).uniqueResult();
        u.getCapasInformacion();
        return u;
    } catch (Throwable t) {
        log.error("Error al buscar el usuario", t);
    }
    return null;
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public List<Usuario> getByFilter(Usuario u) {
    List<Usuario> res = new ArrayList<Usuario>(0);

    org.hibernate.Session currentSession = getSession();
    currentSession.clear();
    Criteria criteria = currentSession.createCriteria(Usuario.class).addOrder(Order.asc("nombreUsuario"));

    if (u.getInfoAdicional() != null)
        criteria = criteria.add(/*from ww  w . j  a v a  2 s .c om*/
                Restrictions.ilike("infoAdicional", LogicConstants.getGenericString(u.getInfoAdicional())));
    if (u.getAdministrador() != null)
        criteria = criteria.add(Restrictions.eq("administrador", u.getAdministrador()));
    if (u.getHabilitado() != null)
        criteria = criteria.add(Restrictions.eq("habilitado", u.getHabilitado()));
    if (u.getNombreUsuario() != null)
        criteria = criteria.add(
                Restrictions.ilike("nombreUsuario", LogicConstants.getGenericString(u.getNombreUsuario())));
    if (u.getNombre() != null)
        criteria = criteria.add(Restrictions.ilike("nombre", LogicConstants.getGenericString(u.getNombre())));
    if (u.getApellidos() != null)
        criteria = criteria
                .add(Restrictions.ilike("apellidos", LogicConstants.getGenericString(u.getApellidos())));
    if (u.getRoles() != null)
        criteria = criteria.createCriteria("roles")
                .add(Restrictions.ilike("nombre", LogicConstants.getGenericString(u.getRoles().getNombre())));

    res = criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

    for (Usuario usu : res)
        if (usu != null) {
            if (usu.getRoles() != null)
                usu.getRoles().getId();
        }

    return res;
}

From source file:es.emergya.bbdd.dao.UsuarioHome.java

License:Open Source License

@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public Calendar lastUpdated() {
    Calendar res = Calendar.getInstance();
    try {/*from   w  w w .  j  a  v  a  2s. co m*/
        org.hibernate.Session currentSession = getSession();
        currentSession.clear();
        Criteria criteria = currentSession.createCriteria(Usuario.class)
                .setProjection(Projections.max("updatedAt"));
        res.setTime((Date) criteria.uniqueResult());
    } catch (Throwable t) {
        log.error(t, t);
        return null;
    }
    return res;
}

From source file:eu.cloudscale.showcase.generate.AGenerate.java

License:Open Source License

@Override
public void populateAddressTable() {
    System.out.println("Populating ADDRESS Table with " + NUM_ADDRESSES + " addresses");
    System.out.print("Complete (in 10,000's): ");
    String ADDR_STREET1, ADDR_STREET2, ADDR_CITY, ADDR_STATE;
    String ADDR_ZIP;/*from w ww  .  j av a 2s.  c  om*/
    int ADDR_CO_ID;

    LinkedList<ICountry> countries = getRandomCountries(NUM_ADDRESSES + 10000);

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    for (int i = 1; i <= NUM_ADDRESSES; i++) {
        IAddress a = addressDao.getObject();

        if (i % 1000 == 0) {
            session.flush();
            session.clear();
            System.out.print((i / 1000) + " ");

        }

        if (i % 10000 == 0) {
            System.out.println();
        }

        ADDR_STREET1 = getRandomAString(15, 40);
        ADDR_STREET2 = getRandomAString(15, 40);
        ADDR_CITY = getRandomAString(4, 30);
        ADDR_STATE = getRandomAString(2, 20);
        ADDR_ZIP = getRandomAString(5, 10);

        // MongoDB doesn't have autoincrement field so we must set ID manually
        if (db instanceof MongoService) {
            a.setAddrId(i);
        }
        a.setAddrStreet1(ADDR_STREET1);
        a.setAddrStreet2(ADDR_STREET2);
        a.setAddrCity(ADDR_CITY);
        a.setAddrState(ADDR_STATE);
        a.setAddrZip(ADDR_ZIP);

        a.setCountry(this.countries.get(getRandomInt(1, this.countries.size() - 1)));

        this.addresses.add(a);
        session.save(a);
    }

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

    addressDao.finish();

    System.out.println("");
}

From source file:eu.cloudscale.showcase.generate.AGenerate.java

License:Open Source License

@Override
public void populateCustomerTable() {
    String C_UNAME, C_PASSWD, C_LNAME, C_FNAME;
    int C_ADDR_ID, C_PHONE;
    String C_EMAIL;//from   w  w  w  .  j  ava 2 s  .  c o  m
    java.sql.Date C_SINCE, C_LAST_LOGIN;
    java.sql.Timestamp C_LOGIN, C_EXPIRATION;
    double C_DISCOUNT, C_BALANCE, C_YTD_PMT;
    java.sql.Date C_BIRTHDATE;
    String C_DATA;
    int i;

    System.out.println("Populating CUSTOMER Table with " + NUM_CUSTOMERS + " customers");
    System.out.print("Complete (in 10,000's): ");

    LinkedList<IAddress> addresses = getRandomAddresses(NUM_CUSTOMERS + 10000);

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    for (i = 1; i <= NUM_CUSTOMERS; i++) {
        ICustomer c = customerDao.getObject();

        if (i % 1000 == 0) {
            session.flush();
            session.clear();
            System.out.print(i / 1000 + " ");
        }

        if (i % 10000 == 0) {
            System.out.println();
        }

        C_UNAME = DigSyl(i, 0).toLowerCase();
        C_PASSWD = C_UNAME.toLowerCase();
        C_LNAME = getRandomAString(8, 15);
        C_FNAME = getRandomAString(8, 15);
        C_PHONE = getRandomNString(9, 16);
        C_EMAIL = C_UNAME + "@" + getRandomAString(2, 9) + ".com";

        GregorianCalendar cal = new GregorianCalendar();
        cal.add(Calendar.DAY_OF_YEAR, -1 * getRandomInt(1, 730));
        C_SINCE = new java.sql.Date(cal.getTime().getTime());
        cal.add(Calendar.DAY_OF_YEAR, getRandomInt(0, 60));
        if (cal.after(new GregorianCalendar()))
            cal = new GregorianCalendar();

        C_LAST_LOGIN = new java.sql.Date(cal.getTime().getTime());
        C_LOGIN = new java.sql.Timestamp(System.currentTimeMillis());
        cal = new GregorianCalendar();
        cal.add(Calendar.HOUR, 2);
        C_EXPIRATION = new java.sql.Timestamp(cal.getTime().getTime());

        C_DISCOUNT = (double) getRandomInt(0, 50) / 100.0;
        C_BALANCE = 0.00;
        C_YTD_PMT = (double) getRandomInt(0, 99999) / 100.0;
        int year = getRandomInt(1880, 2000);
        int month = getRandomInt(0, 11);
        int maxday = 31;
        int day;
        if (month == 3 | month == 5 | month == 8 | month == 10)
            maxday = 30;
        else if (month == 1)
            maxday = 28;
        day = getRandomInt(1, maxday);
        cal = new GregorianCalendar(year, month, day);
        C_BIRTHDATE = new java.sql.Date(cal.getTime().getTime());

        C_DATA = getRandomAString(100, 500);

        // MongoDB doesn't have autoincrement field so we must set ID manually
        if (db instanceof MongoService) {
            c.setCId(i);
        }
        c.setCUname(C_UNAME);
        c.setCPasswd(C_PASSWD);
        c.setCFname(C_FNAME);
        c.setCLname(C_LNAME);

        c.setAddress(this.addresses.get(getRandomInt(1, this.addresses.size() - 1)));
        c.setCPhone(String.valueOf(C_PHONE));
        c.setCEmail(C_EMAIL);
        c.setCSince(C_SINCE);
        c.setCLastVisit(C_LAST_LOGIN);
        c.setCLogin(C_LOGIN);
        c.setCExpiration(C_EXPIRATION);
        c.setCDiscount(C_DISCOUNT);
        c.setCBalance(C_BALANCE);
        c.setCYtdPmt(C_YTD_PMT);
        c.setCBirthdate(C_BIRTHDATE);
        c.setCData(C_DATA);

        this.customers.add(c);
        session.save(c);
    }

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

    System.out.println();
}