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

The following examples show how to use org.hibernate.query.Query#getSingleResult() . 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: Insights   File: ToolsLayoutDAL.java    License: Apache License 2.0 6 votes vote down vote up
public ToolsLayout getToolLayout(String toolName, String toolCategory) {
	Query<ToolsLayout> createQuery = getSession().createQuery(
			"FROM ToolsLayout TL WHERE TL.toolName = :toolName AND TL.toolCategory = :toolCategory",
			ToolsLayout.class);
	createQuery.setParameter("toolName", toolName);
	createQuery.setParameter("toolCategory", toolCategory);
	ToolsLayout toolLayout = null;
	try{
		toolLayout = createQuery.getSingleResult();
	}catch(Exception e){
		throw new RuntimeException("Exception while retrieving data"+e);
	}
	terminateSession();
	terminateSessionFactory();
	return toolLayout;
}
 
Example 2
@Override
public Company getCompanyByName(String companyName) {
	Company company = null;
	try {
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Company> query = session.createQuery("from Company where title = :companyName", Company.class);
		query.setParameter("companyName", companyName);
		query.setMaxResults(1);
		company = query.getSingleResult();
		
		logging.setMessage("CompanyDaoImpl -> fetching by name :" + companyName);
		
	} catch (NoResultException ex) {
		logging.setMessage("CompanyDaoImpl Error -> "+ex.getLocalizedMessage());
	} finally {
		if(session.isOpen()){session.close();}
	}
	return company;
}
 
Example 3
@Override
public String getTotalCreditLiraPaymentsForOneDay(String date) {
    String totalCredit = null;
    try {

        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery(
                "select sum(price) from Payment where "
                + "paymentType = 'CREDIT CARD' and currency = 'TURKISH LIRA' and dateTime >= :date",
                String.class);
        query.setParameter("date", date);
        totalCredit = query.getSingleResult();

        logging.setMessage("PaymentDaoImpl -> fetching total credit pound for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCredit;
}
 
Example 4
@Override
public String getTotalCreditPoundPaymentsForOneDay(String date) {
    String totalCredit = null;
    try {

        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery(
                "select sum(price) from Payment where "
                + "paymentType = 'CREDIT CARD' and currency = 'POUND' and dateTime >= :date",
                String.class);
        query.setParameter("date", date);
        totalCredit = query.getSingleResult();

        logging.setMessage("PaymentDaoImpl -> fetching total credit pound for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCredit;
}
 
Example 5
@Override
public Payment getLastPayment() {
    Payment thePayment = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Payment> query = session.createQuery("from Payment order by Id DESC", Payment.class);
        query.setMaxResults(1);
        thePayment = query.getSingleResult();

        logging.setMessage("PaymentDaoImpl -> fetching last payment for today...");

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return thePayment;
}
 
Example 6
@Override
public Reservation findReservationByRefNo(String refNo) {
    Reservation reservationByRef = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Reservation> query = session.createQuery("from Reservation where referanceNo=:refNo", Reservation.class);
        query.setParameter("refNo", refNo);
        query.setMaxResults(1);
        reservationByRef = query.getSingleResult();

        logging.setMessage("ReservationDaoImpl -> fetching reservation by referance number...");

    } catch (NoResultException e) {
        final InformationFrame frame = new InformationFrame();
        frame.setMessage("There is no reservation with this referance number!");
        frame.setVisible(true);
    } finally {
        session.close();
    }
    return reservationByRef;

}
 
Example 7
@Override
public String getTotalCashLiraPostingsForOneDay(String today) {
    String totalCash = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery("select sum(price) from Posting where currency = 'TURKISH LIRA' and dateTime >= :today", String.class);
        query.setParameter("today", today);
        totalCash = query.getSingleResult();

        logging.setMessage("PostingDaoImpl -> fetching total cash lira posting for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PostingDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCash;
}
 
Example 8
public User getUserByEmail(String theEmail) {
    User theUser = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<User> query = session.createQuery("from User where Email=:theEmail", User.class);
        query.setParameter("theEmail", theEmail);
        
        theUser =  query.getSingleResult();
        logging.setMessage("UserDaoImpl : fetching user who owner of "+theEmail);
        
    } catch (NoResultException e) {
        logging.setMessage("UserDaoImpl Error : " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return theUser;
}
 
Example 9
/**
 * The method count the number of references with '%from%' and 'to' and
 * optional 'type' and optional 'restriction%' values of the table.
 *
 * @param fromtype
 *            a substing in the from ID as String, it can be null
 * @param to
 *            the object ID as String, which is referenced
 * @param type
 *            the refernce type, it can be null
 * @param restriction
 *            a first part of the to ID as String, it can be null
 * @return the number of references
 */
@Override
public final int countTo(String fromtype, String to, String type, String restriction) {
    Session session = getSession();
    Number returns;
    StringBuilder qBf = new StringBuilder(1024);
    qBf.append("select count(key.mcrfrom) from ").append(classname).append(" where MCRTO like ").append('\'')
        .append(to).append('\'');

    if (type != null && type.length() != 0) {
        qBf.append(" and MCRTYPE = \'").append(type).append('\'');
    }
    if (restriction != null && restriction.length() != 0) {
        qBf.append(" and MCRTO like \'").append(restriction).append('\'');
    }
    if (fromtype != null && fromtype.length() != 0) {
        qBf.append(" and MCRFROM like \'%_").append(fromtype).append("_%\'");
    }

    Query<Number> q = session.createQuery(qBf.toString(), Number.class);
    returns = q.getSingleResult();

    return returns.intValue();
}
 
Example 10
@Override
public Room getRoomByRoomNumber(String roomNumber) {

    try {
        
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Room> query = session.createQuery("from Room where number=:roomNumber", Room.class);
        query.setParameter("roomNumber", roomNumber);
        
        logging.setMessage("RoomDaoImpl -> fetching room by number "+roomNumber);
        return query.getSingleResult();

    } catch (NonUniqueResultException e) {
        logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
        final InformationFrame frame = new InformationFrame();
        frame.setMessage("There is more than one room with this number!");
        frame.setVisible(true);
    }
    session.close();
    return null;
}
 
Example 11
@Override
public String getTotalCreditPoundPostingsForOneDay(String date) {
    String totalCredit = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery("select sum(price) from Posting where "
                + "currency = 'CREDIT CARD' and currency = 'POUND' and dateTime >= :date", String.class);
        query.setParameter("date", date);
        totalCredit = query.getSingleResult();

        logging.setMessage("PostingDaoImpl -> fetching total credit card pound posting for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PostingDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCredit;
}
 
Example 12
@Override
public Customer findCustomerByName(String name, String lastName) {
               Customer customer = null;
	try {
		
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Customer> query = session.createQuery("from Customer where FirstName=:name and LastName=:lastName", Customer.class);
		query.setParameter("name", name);
		query.setParameter("lastName", lastName);
		query.setMaxResults(1);
                       
		customer = query.getSingleResult();
		logging.setMessage("CustomerDaoImpl -> fetching customer with name :" + name);
	} catch (NoResultException e) {
		final InformationFrame frame = new InformationFrame();
		frame.setMessage("Customers not found! :" +e.getLocalizedMessage());
		frame.setVisible(true);
	} finally {
		session.close();
	}
               return customer;
}
 
Example 13
Source Project: quickperf   File: UserDao.java    License: Apache License 2.0 5 votes vote down vote up
public User findByEmail(String email) {
	Session session = sessionFactory.getCurrentSession();
	String emailParam = "email";
	String hqlQuery = " FROM " + User.class.getCanonicalName() + " user"
			        + " WHERE user.email =" + ":" + emailParam;
	Query<User> query = session.createQuery(hqlQuery, User.class);
	query.setParameter(emailParam, email);
	return query.getSingleResult();
}
 
Example 14
Source Project: Insights   File: AgentConfigDAL.java    License: Apache License 2.0 5 votes vote down vote up
public AgentConfig updateAgentRunningStatus(String agentId, AGENTACTION action) {
	Query<AgentConfig> createQuery = getSession().createQuery("FROM AgentConfig AC WHERE AC.agentKey = :agentKey",
			AgentConfig.class);
	createQuery.setParameter("agentKey", agentId);
	AgentConfig agentConfig = createQuery.getSingleResult();
	getSession().beginTransaction();
	if (agentConfig != null) {
		agentConfig.setAgentStatus(action.name());
		getSession().update(agentConfig);
	}
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return agentConfig;
}
 
Example 15
Source Project: modeldb   File: ProjectDAORdbImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean projectExistsInDB(String projectId) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(COUNT_PROJECT_BY_ID_HQL);
    query.setParameter("projectId", projectId);
    Long projectCount = (Long) query.getSingleResult();
    return projectCount == 1L;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return projectExistsInDB(projectId);
    } else {
      throw ex;
    }
  }
}
 
Example 16
Source Project: Insights   File: ToolsLayoutDAL.java    License: Apache License 2.0 5 votes vote down vote up
public boolean deleteToolLayout(String toolName, String toolCategory, int agentId) {
	Query<ToolsLayout> createQuery = getSession().createQuery(
			"FROM ToolsLayout TL WHERE TL.toolName = :toolName AND TL.toolCategory = :toolCategory",
			ToolsLayout.class);
	createQuery.setParameter("toolName", toolName);
	createQuery.setParameter("toolCategory", toolCategory);
	ToolsLayout toolLayout = createQuery.getSingleResult();
	getSession().beginTransaction();
	getSession().delete(toolLayout);
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return true;
}
 
Example 17
Source Project: Insights   File: DataTaggingDAL.java    License: Apache License 2.0 5 votes vote down vote up
public boolean deleteEntityData(String hierarchyName) {
	Query<DataTagging> createQuery = getSession().createQuery(
			"FROM DataTagging DT WHERE DT.hierarchyName = :hierarchyName",
			DataTagging.class);
	createQuery.setParameter("hierarchyName", hierarchyName);
	DataTagging dataTagging = createQuery.getSingleResult();
	getSession().beginTransaction();
	getSession().delete(dataTagging);
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return true;
}
 
Example 18
Source Project: Insights   File: WebHookConfigDAL.java    License: Apache License 2.0 5 votes vote down vote up
public Boolean updateWebHookConfiguration(WebHookConfig webhookConfiguration) {
	Query<WebHookConfig> createQuery = getSession()
			.createQuery("FROM WebHookConfig WH WHERE WH.webhookName = :webhookName", WebHookConfig.class);
	createQuery.setParameter("webhookName", webhookConfiguration.getWebHookName());
	WebHookConfig parentConfigList = createQuery.getSingleResult();
	terminateSession();
	if (parentConfigList != null) {
		Set<WebhookDerivedConfig> dataFromUI = webhookConfiguration.getWebhookDerivedConfig();
		parentConfigList.setDataFormat(webhookConfiguration.getDataFormat());
		parentConfigList.setLabelName(webhookConfiguration.getLabelName());
		parentConfigList.setWebHookName(webhookConfiguration.getWebHookName());
		parentConfigList.setToolName(webhookConfiguration.getToolName());
		parentConfigList.setMQChannel(webhookConfiguration.getMQChannel());
		parentConfigList.setSubscribeStatus(webhookConfiguration.getSubscribeStatus());
		parentConfigList.setResponseTemplate(webhookConfiguration.getResponseTemplate());
		parentConfigList.setDynamicTemplate(webhookConfiguration.getDynamicTemplate());
		parentConfigList.setIsUpdateRequired(webhookConfiguration.getIsUpdateRequired());
		parentConfigList.setFieldUsedForUpdate(webhookConfiguration.getFieldUsedForUpdate());
		Set<WebhookDerivedConfig> dataDriverFromTable = parentConfigList.getWebhookDerivedConfig();
		dataDriverFromTable.clear();
		dataDriverFromTable.addAll(dataFromUI);
		parentConfigList.setWebhookDerivedConfig(dataDriverFromTable);
		getSession().beginTransaction();
		getSession().saveOrUpdate(parentConfigList);
		getSession().getTransaction().commit();
		terminateSession();
		terminateSessionFactory();

		return Boolean.TRUE;

	} else {
		return Boolean.FALSE;
	}

}
 
Example 19
Source Project: modeldb   File: DatasetDAORdbImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean datasetExistsInDB(String datasetId) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(COUNT_DATASET_BY_ID_HQL);
    query.setParameter("datasetId", datasetId);
    Long projectCount = (Long) query.getSingleResult();
    return projectCount == 1L;
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return datasetExistsInDB(datasetId);
    } else {
      throw ex;
    }
  }
}
 
Example 20
@Override
public Long getOrganisationUnitHierarchyMemberCount( OrganisationUnit parent, Object member, String collectionName )
{
    final String hql =
        "select count(*) from OrganisationUnit o " +
            "where o.path like :path " +
            "and :object in elements(o." + collectionName + ")";

    Query<Long> query = getTypedQuery( hql );
    query.setParameter( "path", parent.getPath() + "%" )
        .setParameter( "object", member );

    return query.getSingleResult();
}