Java Code Examples for org.hibernate.Criteria#createAlias()

The following examples show how to use org.hibernate.Criteria#createAlias() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public Criteria evaluate(Session session) {

	if (glossaryId == null) {
		logger.debug("SearchGlossaryStructureWithWordLike, glossaryId =null");
		return null;
	}

	Criteria c = session.createCriteria(SbiGlWlist.class, "wlist");
	c.createAlias("wlist.content", "contentWl");
	c.createAlias("contentWl.glossary", "glossaryWl");
	c.createAlias("word", "wordWl");
	// c.createAlias("contentWl.parent", "parent"); // get parent info
	c.add(Restrictions.eq("glossaryWl.glossaryId", Integer.parseInt(glossaryId)));
	if (word != null) {
		c.add(Restrictions.like("wordWl.word", word, MatchMode.ANYWHERE).ignoreCase());
	}

	return c;
}
 
Example 2
@Override
public ServiceInfo lookupService(ServiceName serviceName) {
    Session session = null;

    try {
        session = sessionFactory.openSession();
        Criteria criteria = session.createCriteria(StoredService.class);

        criteria.add(Restrictions.eq("name", serviceName.getServiceName()));
        criteria.createAlias("environment", "environment");
        criteria.add(Restrictions.eq("environment.name", serviceName.getEnvironment()));

        StoredService storedService = (StoredService) criteria.uniqueResult();

        // hotfix to load services from default environment of old DB
        if(storedService == null && serviceName.isDefault()) {
            criteria = session.createCriteria(StoredService.class);
            criteria.add(Restrictions.eq("name", serviceName.getServiceName()));
            criteria.add(Restrictions.isNull("environment"));
            storedService = (StoredService) criteria.uniqueResult();
        }

        return storedService != null ? new ServiceInfo(storedService.getId(), serviceName) : null;
    } catch (RuntimeException e) {
        logger.error("Could not retrieve a service for name: {}", serviceName, e);
        throw new StorageException("Could not retrieve a service for name: " + serviceName, e);
    } finally {
        if(session != null) {
            session.close();
        }
    }

}
 
Example 3
@SuppressWarnings(SUPPRESS_UNCHECKED)
private List<Repository> getAllRepositories(String projectName, ContentType type) {
    final Criteria crit = sessionService.getSession().createCriteria(Repository.class);
    SimpleExpression restriction = Restrictions.eq("contentType", type);
    SimpleExpression bothRestriction = Restrictions.eq("contentType", ContentType.BOTH);
    crit.add(Restrictions.or(restriction, bothRestriction));
    if (projectName != null) {
        crit.createAlias("project", "p");
        crit.add(Restrictions.eq("p.name", projectName));
    }
    List<Repository> list = crit.list();
    HibernateLazyInitializer.initCollection(list);
    return list;
}
 
Example 4
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiGlBnessClsWlist.class, "bnwl");
	c.createAlias("bnwl.word", "worddass");
	// c.createAlias("bnwl.bness_cls", "bness_clsass");
	c.add(Restrictions.eq("bnwl.bness_cls.bcId", id));
	if (column != null && column.compareTo("null") != 0) {
		c.add(Restrictions.eq("bnwl.column_name", column));
	}
	return c;
}
 
Example 5
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiGlDataSetWlist.class, "dwlist");
	if (iddoc != null) {
		c.createAlias("dwlist.word", "wordWl");
		c.add(Restrictions.eq("dwlist.id.datasetId", iddoc));
		if(organiz!=null){
		c.add(Restrictions.eq("dwlist.id.organization", organiz));
		}
	}
	// c.addOrder(Order.asc("word"));
	return c;
}
 
Example 6
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiGlDocWlist.class, "dwlist");
	if (iddoc != null) {
		c.createAlias("dwlist.word", "wordWl");
		c.add(Restrictions.eq("id.documentId", iddoc));
	}
	// c.addOrder(Order.asc("word"));
	return c;
}
 
Example 7
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiGlBnessClsWlist.class, "dwlist");
	if (metaBnessClsId != null) {
		c.createAlias("dwlist.word", "wordWl");
		c.add(Restrictions.eq("dwlist.id.bcId", metaBnessClsId));

	}
	// c.addOrder(Order.asc("word"));
	return c;
}
 
Example 8
@Override
	public Criteria evaluate(Session session) {
		Criteria c = session.createCriteria(SbiGlContents.class,"cont");
//		Criteria c = session.createCriteria(SbiGlWlist.class,"wlist");
		c.createAlias("cont.parent", "par"); 
		c.add(Restrictions.eq("cont.contentId", cont_id));
	
		return c;
	}
 
Example 9
@Override
public Criteria evaluate(Session session) {
	Criteria c;
	
	if(glossary_id==null){
		c = session.createCriteria(SbiGlWord.class,"gl_word");
	}else{
		//filter by glossary
		c = session.createCriteria(SbiGlWlist.class,"wlist");
		c.createAlias("wlist.word", "gl_word");
		c.createAlias("wlist.content", "gl_cont");
		c.add(Restrictions.eq("gl_cont.glossaryId", glossary_id));
	}
	
	
	c.setProjection(Projections.projectionList().add(Projections.property("gl_word.wordId"), "wordId").add(Projections.property("gl_word.word"), "word"))
			.setResultTransformer(Transformers.aliasToBean(SbiGlWord.class));
	if (word != null && !word.isEmpty()) {
		c.add(Restrictions.like("gl_word.word", word, MatchMode.ANYWHERE).ignoreCase());
	}
	if(page!=null && item_per_page!=null ){
		c.setFirstResult((page - 1) * item_per_page);
	     c.setMaxResults(item_per_page);
		}
	c.addOrder(Order.asc("gl_word.word"));
	return c;
}
 
Example 10
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiGlTableWlist.class, "dwlist");
	if (metaTableId != null) {
		c.createAlias("dwlist.word", "wordWl");
		c.add(Restrictions.eq("dwlist.id.tableId", metaTableId));

	}
	// c.addOrder(Order.asc("word"));
	return c;
}
 
Example 11
/**
 * Go through the property name to see if it is a complex one. If it is, aliases must be declared.
 * 
 * @param orgPropertyName
 *            The propertyName. Can be complex.
 * @param userData
 *            The userData object that is passed in each method of the FilterVisitor. Should always be of the info
 *            "Criteria".
 * @return property name
 */
private String parsePropertyName(String orgPropertyName, Object userData) {
	// try to assure the correct separator is used
	String propertyName = orgPropertyName.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR);

	// split the path (separator is defined in the HibernateLayerUtil)
	String[] props = propertyName.split(HibernateLayerUtil.SEPARATOR_REGEXP);
	String finalName;
	if (props.length > 1 && userData instanceof Criteria) {
		// the criteria API requires an alias for each join table !!!
		String prevAlias = null;
		for (int i = 0; i < props.length - 1; i++) {
			String alias = props[i] + "_alias";
			if (!aliases.contains(alias)) {
				Criteria criteria = (Criteria) userData;
				if (i == 0) {
					criteria.createAlias(props[0], alias);
				} else {
					criteria.createAlias(prevAlias + "." + props[i], alias);
				}
				aliases.add(alias);
			}
			prevAlias = alias;
		}
		finalName = prevAlias + "." + props[props.length - 1];
	} else {
		finalName = propertyName;
	}
	return finalName;
}
 
Example 12
@Override
public List<SystemUnderTest> getAllForRunner(String runnerName) {
    final Criteria crit = sessionService.getSession().createCriteria(SystemUnderTest.class);
    crit.createAlias("runner", "r");
    crit.add(Restrictions.eq("r.name", runnerName));
    crit.addOrder(Order.asc(NAME));

    @SuppressWarnings(SUPPRESS_UNCHECKED)
    List<SystemUnderTest> systemUnderTests = crit.list();
    HibernateLazyInitializer.initCollection(systemUnderTests);
    return systemUnderTests;
}
 
Example 13
@Override
public Reference get(Reference reference) {
    final Criteria crit = sessionService.getSession().createCriteria(Reference.class);

    if (StringUtils.isEmpty(reference.getSections())) {
        crit.add(Restrictions.isNull("sections"));
    } else {
        crit.add(Restrictions.eq("sections", reference.getSections()));
    }

    crit.createAlias("requirement", "req");
    crit.add(Restrictions.eq("req.name", reference.getRequirement().getName()));
    crit.createAlias("req.repository", "reqRepo");
    crit.add(Restrictions.eq("reqRepo.uid", reference.getRequirement().getRepository().getUid()));
    crit.createAlias("specification", "spec");
    crit.add(Restrictions.eq("spec.name", reference.getSpecification().getName()));
    crit.createAlias("spec.repository", "specRepo");
    crit.add(Restrictions.eq("specRepo.uid", reference.getSpecification().getRepository().getUid()));
    crit.createAlias(SYSTEM_UNDER_TEST, SUT);
    crit.add(Restrictions.eq(SUT_NAME, reference.getSystemUnderTest().getName()));
    crit.createAlias("sut.project", "sp");
    crit.add(Restrictions.eq("sp.name", reference.getSystemUnderTest().getProject().getName()));

    Reference result = ( Reference ) crit.uniqueResult();
    HibernateLazyInitializer.init(result);
    return result;
}
 
Example 14
@Override
public List<Specification> getAllSpecifications(SystemUnderTest sut) {
    final Criteria crit = sessionService.getSession().createCriteria(Specification.class);
    crit.createAlias("targetedSystemUnderTests", "sut");
    crit.add(Restrictions.eq("sut.name", sut.getName()));
    crit.createAlias("sut.project", "sp");
    crit.add(Restrictions.eq(SP_NAME, sut.getProject().getName()));
    crit.addOrder(Order.asc(SP_NAME));

    @SuppressWarnings(SUPPRESS_UNCHECKED)
    List<Specification> specifications = crit.list();
    HibernateLazyInitializer.initCollection(specifications);
    return specifications;
}
 
Example 15
Source Project: jdal   File: HibernateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create an alias for a property path
 * @return the alias
 */
public static String  createAlias(Criteria criteria, String propertyPath) {
	String[] paths = PropertyUtils.split(propertyPath);
	String alias = "";
	
	for (String name : paths) {
		alias += StringUtils.isEmpty(alias) ? name : "." + name;
		criteria.createAlias(alias, name);
	}
	
	
	return PropertyUtils.getPropertyName(alias);
}
 
Example 16
private void buildCriteria(final Criteria criteria)
{
  for (final Object obj : filterSettings) {
    if (obj instanceof Criterion) {
      criteria.add((Criterion) obj);
    } else if (obj instanceof Order) {
      criteria.addOrder((Order) obj);
    } else if (obj instanceof Alias) {
      final Alias alias = (Alias) obj;
      criteria.createAlias(alias.arg0, alias.arg1, alias.joinType);
    } else if (obj instanceof QueryFilter) {
      final QueryFilter filter = (QueryFilter) obj;
      Criteria subCriteria;
      if (StringUtils.isEmpty(filter.getAlias()) == true) {
        subCriteria = criteria.createCriteria(filter.getName());
      } else {
        subCriteria = criteria.createCriteria(filter.getName(), filter.getAlias());
      }
      filter.buildCriteria(subCriteria);
    }
  }
  if (associationPath != null) {
    criteria.setFetchMode(associationPath, fetchMode);
  }
  if (maxResults > 0) {
    criteria.setMaxResults(maxResults);
  }
}
 
Example 17
@Override
public List<SystemUnderTest> getAllForProject(String projectName) {
    final Criteria crit = sessionService.getSession().createCriteria(SystemUnderTest.class);
    crit.createAlias("project", "p");
    crit.add(Restrictions.eq("p.name", projectName));
    crit.addOrder(Order.asc(NAME));

    @SuppressWarnings(SUPPRESS_UNCHECKED)
    List<SystemUnderTest> systemUnderTests = crit.list();
    HibernateLazyInitializer.initCollection(systemUnderTests);
    return systemUnderTests;
}
 
Example 18
@Override
public Repository getByName(String projectName, String repositoryName) {
    final Criteria crit = sessionService.getSession().createCriteria(Repository.class);
    crit.add(Property.forName("name").eq(repositoryName));
    crit.createAlias("project", "p");
    crit.add(Restrictions.eq("p.name", projectName));
    Repository repository = ( Repository ) crit.uniqueResult();
    HibernateLazyInitializer.init(repository);
    return repository;
}
 
Example 19
@Override
@SuppressWarnings(SUPPRESS_UNCHECKED)
public List<Repository> getAll(String projectName) {
    final Criteria crit = sessionService.getSession().createCriteria(Repository.class);
    if (projectName != null) {
        crit.createAlias("project", "p");
        crit.add(Restrictions.eq("p.name", projectName));
    }
    List<Repository> list = crit.list();
    HibernateLazyInitializer.initCollection(list);
    return list;
}
 
Example 20
/**
 * Load events log by user.
 *
 * @see it.eng.spagobi.events.dao.IEventLogDAO#loadEventsLogByUser(it.eng.spago.security.IEngUserProfile)
 */
@Override
public PagedList<EventLog> loadEventsLogByUser(UserProfile profile, int offset, int fetchsize, Date startDate, Date endDate, String creationUser,
		String type, String sortingColumn, boolean sortingAscending) {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	PagedList<EventLog> toReturn = null;
	// String hql = null;
	// Query hqlQuery = null;

	Collection<String> roles = getUserRoles(profile);
	if (roles == null || roles.size() == 0) {
		return PagedList.emptyList(EventLog.class);
	}

	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		Criteria criteria = getBaseFilteringCriteria(startDate, endDate, creationUser, type, aSession);
		// adding restrictions about user's role
		criteria.createAlias("roles", "role");
		criteria.add(Restrictions.in("role.name", roles));

		int total = getTotalNumber(criteria);

		addOrderingCriteria(criteria, sortingColumn, sortingAscending);

		criteria.setFirstResult(offset);
		criteria.setMaxResults(fetchsize);

		List hibList = criteria.list();

		Iterator it = hibList.iterator();
		List<EventLog> results = new ArrayList<EventLog>();
		while (it.hasNext()) {
			results.add(toEventsLog((SbiEventsLog) it.next()));
		}
		int start = offset + 1;
		toReturn = new PagedList<EventLog>(results, total, start);

	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new SpagoBIRuntimeException("Error while loading events for user " + profile.getUserId(), he);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	logger.debug("OUT");
	return toReturn;
}