Java Code Examples for org.hibernate.query.Query#getResultList()

The following examples show how to use org.hibernate.query.Query#getResultList() . 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
Source Project: tutorials   File: ApplicationView.java    License: MIT License 6 votes vote down vote up
public String[] twoCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    Predicate[] predicates = new Predicate[2];
    predicates[0] = cb.isNull(root.get("itemDescription"));
    predicates[1] = cb.like(root.get("itemName"), "chair%");
    cr.select(root)
        .where(predicates);
    // cr.add(Restrictions.isNull("itemDescription"));
    // cr.add(Restrictions.like("itemName", "chair%"));
    Query<Item> query = session.createQuery(cr);
    final List<Item> notNullItemsList = query.getResultList();
    final String notNullDescItems[] = new String[notNullItemsList.size()];
    for (int i = 0; i < notNullItemsList.size(); i++) {
        notNullDescItems[i] = notNullItemsList.get(i)
            .getItemName();
    }
    session.close();
    return notNullDescItems;
}
 
Example 2
Source Project: tutorials   File: ApplicationView.java    License: MIT License 6 votes vote down vote up
public Double[] projectionAverage() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Double> cr = cb.createQuery(Double.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(cb.avg(root.get("itemPrice")));
    Query<Double> query = session.createQuery(cr);
    final List avgItemPriceList = query.getResultList();
    // session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.avg("itemPrice"))).list();

    final Double avgItemPrice[] = new Double[avgItemPriceList.size()];
    for (int i = 0; i < avgItemPriceList.size(); i++) {
        avgItemPrice[i] = (Double) avgItemPriceList.get(i);
    }
    session.close();
    return avgItemPrice;
}
 
Example 3
Source Project: onedev   File: DefaultIssueManager.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Sessional
@Override
public Collection<String> getUndefinedFields() {
	Collection<String> undefinedFields = getIssueSetting().getUndefinedFields();
	undefinedFields.addAll(roleManager.getUndefinedIssueFields());
	
	Query<String> query = getSession().createQuery("select distinct name from IssueField");
	for (String fieldName: query.getResultList()) {
		FieldSpec field = getIssueSetting().getFieldSpec(fieldName);
		if (field == null)
			undefinedFields.add(fieldName);
	}

	for (Project project: projectManager.query()) 
		undefinedFields.addAll(project.getIssueSetting().getUndefinedFields(project));
	
	for (IssueQuerySetting setting: issueQuerySettingManager.query()) 
		populateUndefinedFields(undefinedFields, setting.getProject(), setting.getUserQueries());
	
	for (User user: userManager.query()) 
		populateUndefinedFields(undefinedFields, null, user.getIssueQuerySetting().getUserQueries());
	
	return undefinedFields;
}
 
Example 4
public List<Customer> getCustomerByReservId(long id) {
	List<Customer> customersList = null;
	try {
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Customer> query = session.createQuery("from Customer where ReservationId=:id", Customer.class);
		query.setParameter("id", id);
		customersList = query.getResultList();
		
                       logging.setMessage("CustomerDaoImpl -> customer updated successfully : "+customersList.toString());
	} catch (NoResultException e) {
		final InformationFrame frame = new InformationFrame();
		frame.setMessage("Customers not found!");
		frame.setVisible(true);
	} finally {
		session.close();
	}
               return customersList;
}
 
Example 5
@Test
public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() {

    prepareData();
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);

    Root<Student> root = criteriaQuery.from(Student.class);
    criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965));

    Query<Student> query = session.createQuery(criteriaQuery);
    List<Student> results = query.getResultList();

    assertNotNull(results);
    assertEquals(1, results.size());

    Student student = results.get(0);

    assertEquals("Ken", student.getFirstName());
    assertEquals("Thompson", student.getLastName());
    assertEquals(1965, student.getGradYear());
}
 
Example 6
Source Project: modeldb   File: LineageDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
private List<LineageEntry> getOutputsByInput(Session session, LineageEntry input) {
  Query query =
      session.createQuery(
          "from LineageEntity where inputExternalId = '"
              + input.getExternalId()
              + "' and inputType = '"
              + input.getTypeValue()
              + "'");
  List<LineageEntry> result = new LinkedList<>();
  for (Object r : query.getResultList()) {
    LineageEntity lineageEntity = (LineageEntity) r;
    result.add(
        LineageEntry.newBuilder()
            .setTypeValue(lineageEntity.getOutputType())
            .setExternalId(lineageEntity.getOutputExternalId())
            .build());
  }
  return result;
}
 
Example 7
public List<Payment> getAllPaymentsForToday(String today) {
    List<Payment> paymentsList = null;
    try {

        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Payment> query = session.createQuery("from Payment where dateTime >= :today", Payment.class);
        query.setParameter("today", today);
        paymentsList = query.getResultList();

        logging.setMessage("PaymentDaoImpl -> fetching all payments for today...");

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return paymentsList;
}
 
Example 8
@Override
public List<Company> getAllCompanies() {
	List<Company> companiesList = null;
	try {
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Company> query = session.createQuery("from Company", Company.class);
		companiesList = query.getResultList();
		
		logging.setMessage("CompanyDaoImpl -> fetching all companies...");
		
	} catch (HibernateException ex) {
		logging.setMessage("CompanyDaoImpl Error -> "+ex.getLocalizedMessage());
	} finally {
		if(session.isOpen()){session.close();}
	}
	return companiesList;
}
 
Example 9
Source Project: butterfly   File: EventSaveDataDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all event progress for a user.
 * @param user The user for the events
 * @return A list of matching records
 */
public List<EventSaveData> findByUser(final UserProfile user) {
    final Query<EventSaveData> query = this.getCurrentSession().createQuery("from EventSaveData where user = :user");
    query.setParameter("user", user);

    return query.getResultList();
}
 
Example 10
Source Project: Insights   File: ToolsLayoutDAL.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> getDistinctToolNames() {
	Query<String> createQuery = getSession().createQuery(
			"SELECT DISTINCT TL.toolName FROM ToolsLayout TL",
			String.class);
	List<String> resultList = createQuery.getResultList();
	terminateSession();
	terminateSessionFactory();
	return resultList;
}
 
Example 11
Source Project: butterfly   File: UserSongRecordDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all song records for a machine.
 * @param pcbid The PCBID of the machine to query for
 * @return A list of matching records
 */
public List<UserSongRecord> findByMachine(final String pcbid) {
    final Query<UserSongRecord> query = this.getCurrentSession().createQuery("from UserSongRecord r where r.machinePcbId = :pcbid");
    query.setParameter("pcbid", pcbid);

    return query.getResultList();
}
 
Example 12
@Override
public List<Customer> getAllCustomers() {
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Customer> query = session.createQuery("from Customer", Customer.class);
		List<Customer> customerList =  query.getResultList();
           session.close();            
		logging.setMessage("CustomerDaoImpl -> fetching all customers");
		
         return customerList;
}
 
Example 13
Source Project: Insights   File: CustomDashboardDAL.java    License: Apache License 2.0 5 votes vote down vote up
public List<CustomDashboard> getCustomDashboard(UserPortfolioEnum portfolio){
	Query<CustomDashboard> createQuery = getSession().createQuery("FROM CustomDashboard C WHERE C.portfolio = :portfolio", CustomDashboard.class);
	createQuery.setParameter("portfolio", portfolio);
	List<CustomDashboard> result = createQuery.getResultList();
	terminateSession();
	terminateSessionFactory();
	return result;
}
 
Example 14
Source Project: mybatis-test   File: HibernateTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJpaCriteria() throws ParseException {
    System.out.println("---------------------------✨ JPA Criteria ✨------------------------");

    Session session = null;
    try {
        session = buildSessionFactory.openSession();
        CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
        CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);

        // 定义 FROM 子句
        Root<Article> article = criteriaQuery.from(Article.class);

        // 构建查询条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Predicate greaterThan = criteriaBuilder.greaterThan(article.get("createTime"), sdf.parse("2018.06.10"));
        Predicate equal = criteriaBuilder.equal(article.get("author"), "coolblog.xyz");

        // 通过具有语义化的方法构建 SQL,等价于 SELECT ... FROM article WHERE ... AND ...
        criteriaQuery.select(article).where(equal, greaterThan);

        Query<Article> query = session.createQuery(criteriaQuery);
        List<Article> articles = query.getResultList();

        System.out.println("JPA Criteria Query Result: ");
        articles.forEach(System.out::println);
    } finally {
        if (Objects.nonNull(session)) {
            session.close();
        }
    }

}
 
Example 15
Source Project: Course-System-Back   File: ClassDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<Clas> selectAllClass() {
	// TODO Auto-generated method stub
	String hql = "from Clas";
	Query<?> query = sessionFactory.getCurrentSession().createQuery(hql);
	@SuppressWarnings("unchecked")
	List<Clas> list = (List<Clas>) query.getResultList();
	return list;
}
 
Example 16
Source Project: onedev   File: DefaultIssueManager.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Sessional
@Override
public Collection<UndefinedFieldValue> getUndefinedFieldValues() {
	Collection<UndefinedFieldValue> undefinedFieldValues = getIssueSetting().getUndefinedFieldValues();
	
	Query query = getSession().createQuery("select distinct name, value from IssueField where type=:choice");
	query.setParameter("choice", FieldSpec.ENUMERATION);
	for (Object[] row: (List<Object[]>)query.getResultList()) {
		String fieldName = (String) row[0];
		String fieldValue = (String) row[1];
		SpecifiedChoices specifiedChoices = SpecifiedChoices.of(getIssueSetting().getFieldSpec(fieldName));
		if (specifiedChoices != null && fieldValue != null 
				&& !specifiedChoices.getChoiceValues().contains(fieldValue)) {
			undefinedFieldValues.add(new UndefinedFieldValue(fieldName, fieldValue));
		}
	}

	for (Project project: projectManager.query())
		undefinedFieldValues.addAll(project.getIssueSetting().getUndefinedFieldValues(project));
	
	for (IssueQuerySetting setting: issueQuerySettingManager.query()) 
		populateUndefinedFieldValues(undefinedFieldValues, setting.getProject(), setting.getUserQueries());
	
	for (User user: userManager.query()) 
		populateUndefinedFieldValues(undefinedFieldValues, null, user.getIssueQuerySetting().getUserQueries());
	
	return undefinedFieldValues;
}
 
Example 17
@Override
public List<ValidationResult> query( ValidationResultQuery validationResultQuery )
{
    Query<ValidationResult> hibernateQuery = getQuery( "from ValidationResult vr" + getRestrictions( "where" ) );

    if ( !validationResultQuery.isSkipPaging() )
    {
        Pager pager = validationResultQuery.getPager();
        hibernateQuery.setFirstResult( pager.getOffset() );
        hibernateQuery.setMaxResults( pager.getPageSize() );
    }

    return hibernateQuery.getResultList();
}
 
Example 18
Source Project: Insights   File: DataTaggingDAL.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> fetchEntityHierarchyName() {
	Query<String> createQuery = getSession().createQuery("SELECT DISTINCT DT.hierarchyName FROM DataTagging DT",String.class);
	List<String> resultList = createQuery.getResultList();
	terminateSession();
	terminateSessionFactory();
	return resultList;
}
 
Example 19
@Override
@SuppressWarnings("unchecked")
public Collection<String> getLinksFromCategoryForType(MCRCategoryID id, String type) {
    Query<?> q = HIB_CONNECTION_INSTANCE.getNamedQuery(NAMED_QUERY_NAMESPACE + "ObjectIDByCategoryAndType");
    q.setCacheable(true);
    q.setParameter("id", id);
    q.setParameter("type", type);
    q.setReadOnly(true);
    return (Collection<String>) q.getResultList();
}
 
Example 20
@Override
public List<PotentialDuplicate> getAllByQuery( PotentialDuplicateQuery query )
{
    if ( query.getTeis() != null && query.getTeis().size() > 0 )
    {
        Query<PotentialDuplicate> hibernateQuery = getTypedQuery(
            "from PotentialDuplicate pr where pr.teiA in (:uids)  or pr.teiB in (:uids)" );
        hibernateQuery.setParameterList( "uids", query.getTeis() );
        return hibernateQuery.getResultList();
    }
    else
    {
        return getAll();
    }
}