List of usage examples for org.hibernate.criterion Restrictions like
public static SimpleExpression like(String propertyName, Object value)
From source file:ca.myewb.controllers.common.PostList.java
License:Open Source License
private void addFilter(String filter, Criteria criteria) { if (filter == null) { return; // just in case }//from w w w . jav a 2 s.co m log.debug("Filtering posts: " + filter); TagModel t = TagModel.getTag(filter); criteria.createAlias("tags", "t"); if (t == null) //won't find anything { criteria.add(Restrictions.like("t.name", "%" + filter + "%")); } else //broaden the search { criteria.add(Restrictions.like("t.name", "%" + t.getName() + "%")); } }
From source file:ca.qc.cegepoutaouais.tge.pige.server.PigeHibernateUtil.java
License:Open Source License
private static SimpleExpression createLikeRestriction(FilterConfig config, MatchMode matchMode) { if (config.getField().equals(User.ROLE_REF)) { return Restrictions.like(config.getField(), (Role) config.getValue()); } else {//from w w w .ja v a 2s.co m return Restrictions.like(config.getField(), (String) config.getValue(), matchMode); } }
From source file:cn.newtouch.hibernate.dao.StudentDAO.java
License:Open Source License
public static void main(String[] args) { try {// w w w . jav a 2 s . c om Session session = HibernateUtil.getSession(); String hql = " from Student"; List<Student> userList = session.createQuery(hql).list(); System.out.println("=====1=======" + userList.size()); Criteria criteria = session.createCriteria(Student.class); // criteria.add(Restrictions.eq("name", "HZZ")); // map criteria.add(Restrictions.allEq(new HashMap<String, String>())); // criteria.add(Restrictions.gt("id", new Long(1))); // criteria.add(Restrictions.ge("id", new Long(1))); // ? criteria.add(Restrictions.lt("id", new Long(1))); // ? criteria.add(Restrictions.le("id", new Long(1))); // xxxyyy criteria.add(Restrictions.between("id", new Long(1), new Long(2))); // ? criteria.add(Restrictions.like("name", "H")); // and? criteria.add(Restrictions.and(Restrictions.ge("id", new Long(1)), Restrictions.ge("id", new Long(1)))); // or? criteria.add(Restrictions.or(Restrictions.ge("id", new Long(1)), Restrictions.ge("id", new Long(1)))); userList = criteria.list(); System.out.println("=====2=======" + userList.size()); Student student = new Student(); student.setId(123456L); student.setName("hzz"); student.setAge(14); save(student); System.out.println("OK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } catch (Exception e) { e.printStackTrace(); } }
From source file:co.com.codesoftware.logic.ProductoLogic.java
public ProductoEntity consultaProductosFiltro(String codigoBarras, String codigoExterno) { ProductoEntity respuesta = null;/*from www . j ava 2 s. co m*/ System.out.println("" + codigoBarras); try { this.initOperation(); Criteria crit = sesion.createCriteria(ProductoEntity.class); if (codigoBarras != null && !"".equalsIgnoreCase(codigoBarras)) { crit.add(Restrictions.like("codigoBarras", codigoBarras)); } else if (codigoExterno != null && !"".equalsIgnoreCase(codigoExterno)) { crit.add(Restrictions.like("codigoExt", codigoExterno)); } crit.add(Restrictions.eq("estado", "A")); respuesta = (ProductoEntity) crit.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return respuesta; }
From source file:co.com.codesoftware.logica.contabilidad.PucLogica.java
/** * Funcion con la cual obtengo los auxiliares contables por medio de algun criterio * @param criterio//from ww w . j av a 2 s .co m * @return */ public List<AuxContableEntity> obtenerAuxiliaresConXCriterio(String criterio) { List<AuxContableEntity> rta = null; try { this.initOperation(); Criteria crit = this.sesion.createCriteria(AuxContableEntity.class); Criterion uno = Restrictions.like("codigo", "%" + criterio + "%").ignoreCase(); Criterion dos = Restrictions.like("nombre", "%" + criterio + "%").ignoreCase(); crit.add(Restrictions.or(uno, dos)); crit.addOrder(Order.asc("id")); rta = crit.list(); } catch (Exception e) { e.printStackTrace(); } return rta; }
From source file:co.edu.utb.softeng.springtodos.dao.security.impl.UserDaoImpl.java
@Override public User findByUserName(String username) { Session session = sessionFactory.getCurrentSession(); User u = (User) session.createCriteria(User.class).add(Restrictions.like("username", username)) .uniqueResult();/*from w w w. j a v a2 s .c o m*/ return u; }
From source file:com.abiquo.abiserver.commands.UserCommand.java
License:Mozilla Public License
/** * Returns a list of users stored in the Data Base * /*from w ww .jav a2s. co m*/ * @param userSession * @param userListOptions an UserListOptions object containing the options to retrieve the list * of users * @return A DataResult object containing an UserListResult object with an ArrayList of User and * the number of total users */ @SuppressWarnings("unchecked") protected DataResult<UserListResult> getUsers(UserSession userSession, UserListOptions userListOptions) { DataResult<UserListResult> dataResult = new DataResult<UserListResult>(); UserListResult userListResult = new UserListResult(); Session session = null; Transaction transaction = null; try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); // Getting the user that called this method UserHB userHB = (UserHB) session.createCriteria(UserHB.class) .add(Restrictions.eq("user", userSession.getUser())).uniqueResult(); // getUsers has two different authorization resources // If the user who called this method, does not match the security level for the // authorization resource // USER_GET_ALL_USERS, this method will only return those users who belongs to the same // enterprise than // the user that called this method // Getting the authorization resource USER_GET_ALL_USERS AuthResourceHB authResourceHB = (AuthResourceHB) session.createCriteria(AuthResourceHB.class) .add(Restrictions.eq("name", "USER_GET_ALL_USERS")).uniqueResult(); // Checking if the user has not the necessary security level to see the whole list of // Users. If so, we force // the userListOptions object to filter by the enterprise assigned to the user if (authResourceHB.getRoleHB().getSecurityLevel() .compareTo(userHB.getRoleHB().getSecurityLevel()) == -1) { // NOT GRANTED! userListOptions.setByEnterprise((Enterprise) userHB.getEnterpriseHB().toPojo()); } // Creating users criteria Criteria usersListCriteria = session.createCriteria(UserHB.class); Criteria usersCountCriteria = session.createCriteria(UserHB.class); // Removing the users that are deleted usersListCriteria.add(Restrictions.eq("deleted", 0)); usersCountCriteria.add(Restrictions.eq("deleted", 0)); // Adding filter by name, surname or email Disjunction filterDisjunction = Restrictions.disjunction(); if (userListOptions.getFilter().length() > 0) { filterDisjunction.add(Restrictions.like("name", '%' + userListOptions.getFilter() + '%')); filterDisjunction.add(Restrictions.like("surname", '%' + userListOptions.getFilter() + '%')); filterDisjunction.add(Restrictions.like("email", '%' + userListOptions.getFilter() + '%')); } usersListCriteria.add(filterDisjunction); usersCountCriteria.add(filterDisjunction); // Adding filter by Enterprise if (userListOptions.getByEnterprise() != null) { usersListCriteria.add(Restrictions.eq("enterpriseHB", (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB())); usersCountCriteria.add(Restrictions.eq("enterpriseHB", (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB())); } // Adding order // Little fix to match the object used in Hibernate if (userListOptions.getOrderBy().compareTo("role") == 0) userListOptions.setOrderBy("roleHB"); Order order; if (userListOptions.getAsc()) order = Order.asc(userListOptions.getOrderBy()); else order = Order.desc(userListOptions.getOrderBy()); usersListCriteria.addOrder(order); usersCountCriteria.addOrder(order); // Adding filter to get only the users that currently have an active session if (userListOptions.getLoggedOnly()) { ArrayList<String> currentLoggedUsers = (ArrayList<String>) session .createSQLQuery("SELECT user FROM session WHERE expireDate > CURRENT_TIMESTAMP()").list(); usersListCriteria.add(Restrictions.in("user", currentLoggedUsers)); usersCountCriteria.add(Restrictions.in("user", currentLoggedUsers)); } // Once we have the criteria... // 1. Getting the total number of users that match userListOptions Integer totalUsers = (Integer) usersCountCriteria.setProjection(Projections.rowCount()).uniqueResult(); // 2. Getting the list of users, applying an offset and a max of results ArrayList<UserHB> usersHB = (ArrayList<UserHB>) usersListCriteria .setFirstResult(userListOptions.getOffset()).setMaxResults(userListOptions.getLength()).list(); // Building result ArrayList<User> usersList = new ArrayList<User>(); for (UserHB userToReturnHB : usersHB) { usersList.add((User) userToReturnHB.toPojo()); } userListResult.setTotalUsers(totalUsers); userListResult.setUsersList(usersList); transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) transaction.rollback(); this.errorManager.reportError(resourceManager, dataResult, "getUsers", e); return dataResult; } dataResult.setData(userListResult); dataResult.setSuccess(true); dataResult.setMessage(UserCommand.resourceManager.getMessage("getUsers.success")); return dataResult; }
From source file:com.abiquo.abiserver.commands.UserCommand.java
License:Mozilla Public License
/** * Gets the List of enterprises from the Data Base. Enterprises marked as deleted will not be * returned//from w w w . ja v a 2 s. co m * * @param userSession A UserSession object containing the information of the user that called * this method * @param enterpriseListOptions an UserListOptions object containing the options to retrieve the * list of users * @return A DataResult object containing an EnterpriseListResult object */ @SuppressWarnings("unchecked") protected DataResult<EnterpriseListResult> getEnterprises(UserSession userSession, EnterpriseListOptions enterpriseListOptions) { DataResult<EnterpriseListResult> dataResult = new DataResult<EnterpriseListResult>(); Session session = null; Transaction transaction = null; try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); ArrayList<Enterprise> enterpriseList = new ArrayList<Enterprise>(); Integer totalEnterprises = 0; // Getting the user that called this method UserHB userHB = (UserHB) session.createCriteria(UserHB.class) .add(Restrictions.eq("user", userSession.getUser())).uniqueResult(); // getEnterprises has two different authorization resources // If the user who called this method, does not match the security level for the // authorization resource // ENTERPRISE_GET_ALL_ENTERPRISES, this method will only return the enterprise to which // the user belongs // Getting the authorization resources ENTERPRISE_GET_ALL_ENTERPRISES AuthResourceHB authResourceHB = (AuthResourceHB) session.createCriteria(AuthResourceHB.class) .add(Restrictions.eq("name", "ENTERPRISE_GET_ALL_ENTERPRISES")).uniqueResult(); // Checking if the user has a security level equal or higher than the necessary for // retrieve the whole list of // enterprises. Tip: in securityLevel scale, 1 is the greater level of security, and 99 // the lowest if (authResourceHB.getRoleHB().getSecurityLevel() .compareTo(userHB.getRoleHB().getSecurityLevel()) > -1) { // GRANTED! This User can view other Enterprises than the one to he belongs // Creating enterprises criteria Criteria enterprisesListCriteria = session.createCriteria(EnterpriseHB.class); Criteria enterprisesCountCriteria = session.createCriteria(EnterpriseHB.class); // Removing the enterprises that are deleted enterprisesListCriteria.add(Restrictions.eq("deleted", 0)); enterprisesCountCriteria.add(Restrictions.eq("deleted", 0)); // Adding filter text enterprisesListCriteria .add(Restrictions.like("name", '%' + enterpriseListOptions.getFilter() + '%')); enterprisesCountCriteria .add(Restrictions.like("name", '%' + enterpriseListOptions.getFilter() + '%')); // Adding order enterprisesListCriteria.addOrder(Order.asc("name")); // Once we have the criteria... // 1. Getting the total number of enterprises that match enterpriseListOptions totalEnterprises = (Integer) enterprisesCountCriteria.setProjection(Projections.rowCount()) .uniqueResult(); // 2. Getting the list of enterprises, applying an offset and a max of results ArrayList<EnterpriseHB> enterpriseHBList = (ArrayList<EnterpriseHB>) enterprisesListCriteria .setFirstResult(enterpriseListOptions.getOffset()) .setMaxResults(enterpriseListOptions.getLength()).list(); // Building result for (EnterpriseHB enterpriseHB : enterpriseHBList) { enterpriseList.add((Enterprise) enterpriseHB.toPojo()); } } else { // NOT GRANTED! This User can only view the Enterprise to which he belongs enterpriseList.add((Enterprise) userHB.getEnterpriseHB().toPojo()); totalEnterprises = 1; } transaction.commit(); EnterpriseListResult enterpriseListResult = new EnterpriseListResult(); enterpriseListResult.setEnterprisesList(enterpriseList); enterpriseListResult.setTotalEnterprises(totalEnterprises); dataResult.setSuccess(true); dataResult.setData(enterpriseListResult); dataResult.setMessage(UserCommand.resourceManager.getMessage("getEnterprises.success")); } catch (Exception e) { if (transaction != null && transaction.isActive()) transaction.rollback(); this.errorManager.reportError(resourceManager, dataResult, "getEnterprises", e); } return dataResult; }
From source file:com.abiquo.networking.InetManagerMainPolicy.java
License:Mozilla Public License
@Override public IPAddress requestIPAddressVM(Integer dataCenterId, String virtualMachineId) { IPAddress reqAddress = null;// w w w. ja v a2 s .com VirtualMachineIPHB reqVM = null; // check the correct parameters if (dataCenterId == null || virtualMachineId == null) { return null; } // Check if datacenter exists DatacentersIPHB reqDatacenter = (DatacentersIPHB) datacentersDAO.findById(dataCenterId); if (reqDatacenter == null) { return null; } // Check if virtual machine exists reqVM = (VirtualMachineIPHB) virtualMachineDAO.findById(virtualMachineId); if (reqVM != null) { // Check if virtual machine belongs to the given datacenter if (reqVM.getDatacenterId().compareTo(reqDatacenter.getId()) == 0) { reqAddress = IPAddress.newIPAddress(reqVM.getVirtualIP()); } // else will return null } else { // getting all the virtual machines filtering by datacenter Id Criterion filter = Restrictions.like("datacenterId", dataCenterId); List<VirtualMachineIPHB> listVM = virtualMachineDAO.findByCriteria(filter); // check if all the nodes of the datacenter are busy if (listVM.size() == reqDatacenter.getNumNodes()) { System.out.println("No more virtual machines available in this Datacenter!"); return null; } // first, we set the list of IP's List<String> listIP = new ArrayList<String>(); for (int i = 0; i < listVM.size(); i++) { listIP.add(listVM.get(i).getVirtualIP()); } // initialize the variables to assign new IP boolean registeredIP = true; Integer numberIPs = reqDatacenter.getNumNodes(); IPAddress nextIP = IPAddress.newIPAddress(reqDatacenter.getFirstIP()).nextIPAddress(); while (numberIPs > 0 && registeredIP) { if (!listIP.contains(nextIP.toString())) { reqAddress = nextIP; // set the entity to store reqVM = new VirtualMachineIPHB(); reqVM.setId(virtualMachineId); reqVM.setDatacenterId(dataCenterId); reqVM.setVirtualIP(reqAddress.toString()); // store it virtualMachineDAO.makePersistent(reqVM); // set the variable to exit the bucle registeredIP = false; } else { nextIP = nextIP.nextIPAddress(); numberIPs--; } } } return reqAddress; }
From source file:com.abiquo.server.core.cloud.VirtualApplianceDAO.java
License:Open Source License
private Criterion filterBy(final String filter) { Disjunction filterDisjunction = Restrictions.disjunction(); filterDisjunction.add(Restrictions.like(VirtualAppliance.NAME_PROPERTY, '%' + filter + '%')); return filterDisjunction; }