Here are the examples of the java api org.hibernate.query.Query.list() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
108 Examples
19
Source : VersioningUtils.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
public static Set<ArtifactPartEnreplacedy> getArtifactPartEnreplacedies(Session session, String artifactId, int artifactType) {
String queryString = "From " + ArtifactPartEnreplacedy.clreplaced.getSimpleName() + " arp WHERE arp.artifact_type = :artifactType AND arp.artifact_id = :artifactId";
Query query = session.createQuery(queryString);
query.setParameter("artifactType", artifactType);
query.setParameter("artifactId", artifactId);
List<ArtifactPartEnreplacedy> artifactPartEnreplacedies = query.list();
return new HashSet<>(artifactPartEnreplacedies);
}
19
Source : VersioningUtils.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
/**
* Returns the parents of a commit sorted in descending orderof time
*
* @param session
* @param commitSHA
* @return
*/
// TODO: RepoDAO.listBranchCommits should use this
public static List<CommitEnreplacedy> getParentCommits(Session session, String commitSHA) {
List<String> childCommitSHAs = new LinkedList<String>();
childCommitSHAs.add(commitSHA);
List<String> commitSHAs = new LinkedList<>();
while (!childCommitSHAs.isEmpty()) {
String childCommit = childCommitSHAs.remove(0);
commitSHAs.add(childCommit);
@SuppressWarnings("unchecked")
Query<String> sqlQuery = session.createSQLQuery(GET_PARENT_COMMIT_SHA_PREFIX + childCommit + "\'");
List<String> parentCommitSHAs = sqlQuery.list();
childCommitSHAs.addAll(parentCommitSHAs);
}
String getChildCommits = "FROM " + CommitEnreplacedy.clreplaced.getSimpleName() + " c WHERE c.commit_hash IN (:childCommitSHAs) ORDER BY c.date_created DESC";
@SuppressWarnings("unchecked")
Query<CommitEnreplacedy> query = session.createQuery(getChildCommits);
query.setParameterList("childCommitSHAs", commitSHAs);
return query.list();
}
19
Source : DatasetBlobFactory.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
static PathDatasetBlob getPathBlob(Session session, String blobHash) {
String pathComponentQueryHQL = "From " + PathDatasetComponentBlobEnreplacedy.clreplaced.getSimpleName() + " p WHERE p.id.path_dataset_blob_id = :blobShas";
Query<PathDatasetComponentBlobEnreplacedy> pathComponentQuery = session.createQuery(pathComponentQueryHQL);
pathComponentQuery.setParameter("blobShas", blobHash);
List<PathDatasetComponentBlobEnreplacedy> pathDatasetComponentBlobEnreplacedies = pathComponentQuery.list();
if (pathDatasetComponentBlobEnreplacedies != null && pathDatasetComponentBlobEnreplacedies.size() > 0) {
List<PathDatasetComponentBlob> componentBlobs = pathDatasetComponentBlobEnreplacedies.stream().map(PathDatasetComponentBlobEnreplacedy::toProto).collect(Collectors.toList());
return PathDatasetBlob.newBuilder().addAllComponents(componentBlobs).build();
} else {
return null;
}
}
19
Source : DatasetBlobFactory.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
private static S3DatasetBlob getS3Blob(Session session, String blobHash) throws ModelDBException {
String s3ComponentQueryHQL = "From " + S3DatasetComponentBlobEnreplacedy.clreplaced.getSimpleName() + " s3 WHERE s3.id.s3_dataset_blob_id = :blobShas";
Query<S3DatasetComponentBlobEnreplacedy> s3ComponentQuery = session.createQuery(s3ComponentQueryHQL);
s3ComponentQuery.setParameter("blobShas", blobHash);
List<S3DatasetComponentBlobEnreplacedy> datasetComponentBlobEnreplacedies = s3ComponentQuery.list();
if (datasetComponentBlobEnreplacedies != null && datasetComponentBlobEnreplacedies.size() > 0) {
List<S3DatasetComponentBlob> componentBlobs = datasetComponentBlobEnreplacedies.stream().map(S3DatasetComponentBlobEnreplacedy::toProto).collect(Collectors.toList());
return S3DatasetBlob.newBuilder().addAllComponents(componentBlobs).build();
} else {
throw new ModelDBException("S3 dataset Blob not found", Status.Code.NOT_FOUND);
}
}
19
Source : DatasetBlobFactory.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
static QueryDatasetBlob getQueryBlob(Session session, String blobHash) {
String pathComponentQueryHQL = "From " + QueryDatasetComponentBlobEnreplacedy.clreplaced.getSimpleName() + " q WHERE q.id.query_dataset_blob_id = :blobShas";
Query<QueryDatasetComponentBlobEnreplacedy> queryComponentQuery = session.createQuery(pathComponentQueryHQL);
queryComponentQuery.setParameter("blobShas", blobHash);
List<QueryDatasetComponentBlobEnreplacedy> queryDatasetComponentBlobEnreplacedies = queryComponentQuery.list();
if (queryDatasetComponentBlobEnreplacedies != null && queryDatasetComponentBlobEnreplacedies.size() > 0) {
List<QueryDatasetComponentBlob> componentBlobs = queryDatasetComponentBlobEnreplacedies.stream().map(QueryDatasetComponentBlobEnreplacedy::toProto).collect(Collectors.toList());
return QueryDatasetBlob.newBuilder().addAllComponents(componentBlobs).build();
} else {
return null;
}
}
19
Source : ConfigBlobFactory.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
public Blob getBlob(Session session) throws ModelDBException {
String configQuery = "From " + ConfigBlobEnreplacedy.clreplaced.getSimpleName() + " where blob_hash = :blobHash ORDER BY config_seq_number ASC";
Query<ConfigBlobEnreplacedy> query = session.createQuery(configQuery);
query.setParameter("blobHash", getElementSha());
List<ConfigBlobEnreplacedy> configBlobEnreplacedies = query.list();
ConfigBlob.Builder configBlobBuilder = ConfigBlob.newBuilder();
for (ConfigBlobEnreplacedy configBlobEnreplacedy : configBlobEnreplacedies) {
switch(getElementType()) {
case CONFIG_BLOB:
switch(configBlobEnreplacedy.getHyperparameter_type()) {
case HYPERPARAMETER:
HyperparameterElementConfigBlobEnreplacedy elementConfigBlobEnreplacedy = session.get(HyperparameterElementConfigBlobEnreplacedy.clreplaced, configBlobEnreplacedy.getComponentBlobHash());
HyperparameterConfigBlob hyperparameterConfigBlob = HyperparameterConfigBlob.newBuilder().setName(elementConfigBlobEnreplacedy.getName()).setValue(elementConfigBlobEnreplacedy.toProto()).build();
configBlobBuilder.addHyperparameters(hyperparameterConfigBlob);
break;
case HYPERPARAMETER_SET:
HyperparameterSetConfigBlobEnreplacedy setConfigBlobEnreplacedy = session.get(HyperparameterSetConfigBlobEnreplacedy.clreplaced, configBlobEnreplacedy.getComponentBlobHash());
configBlobBuilder.addHyperparameterSet(setConfigBlobEnreplacedy.toProto());
break;
default:
throw new ModelDBException("Unknown blob type found", Status.Code.INTERNAL);
}
break;
default:
throw new ModelDBException("Unknown blob type found", Status.Code.INTERNAL);
}
}
return Blob.newBuilder().setConfig(configBlobBuilder.build()).build();
}
19
Source : SoftDeleteProjects.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
protected ReconcileResult reconcile(Set<String> ids) {
LOGGER.debug("Reconciling projects " + ids.toString());
roleService.deleteEnreplacedyResourcesWithServiceUser(new ArrayList<>(ids), ModelDBResourceEnum.ModelDBServiceResourceTypes.PROJECT);
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
String projectsQueryString = String.format("from %s where id in (:ids)", ProjectEnreplacedy.clreplaced.getSimpleName());
Query projectDeleteQuery = session.createQuery(projectsQueryString);
projectDeleteQuery.setParameter("ids", ids);
List<ProjectEnreplacedy> projectEnreplacedies = projectDeleteQuery.list();
Transaction transaction = session.beginTransaction();
String updateDeletedChildren = String.format("UPDATE %s SET deleted=:deleted WHERE project_id IN (:ids)", ExperimentEnreplacedy.clreplaced.getSimpleName());
Query updateDeletedChildrenQuery = session.createQuery(updateDeletedChildren);
updateDeletedChildrenQuery.setParameter("deleted", true);
updateDeletedChildrenQuery.setParameter("ids", ids);
updateDeletedChildrenQuery.executeUpdate();
transaction.commit();
// TODO: figure out if doing a single query to delete all projects
for (ProjectEnreplacedy projectEnreplacedy : projectEnreplacedies) {
transaction = session.beginTransaction();
session.delete(projectEnreplacedy);
transaction.commit();
}
}
return new ReconcileResult();
}
19
Source : SoftDeleteExperiments.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
protected ReconcileResult reconcile(Set<String> ids) {
LOGGER.debug("Reconciling experiments " + ids.toString());
deleteRoleBindings(ids);
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
String experimentQueryString = String.format("from %s where id in (:ids)", ExperimentEnreplacedy.clreplaced.getSimpleName());
Query<ExperimentEnreplacedy> experimentDeleteQuery = session.createQuery(experimentQueryString, ExperimentEnreplacedy.clreplaced);
experimentDeleteQuery.setParameter("ids", ids);
List<ExperimentEnreplacedy> experimentEnreplacedies = experimentDeleteQuery.list();
Transaction transaction = session.beginTransaction();
String updateDeletedChildren = String.format("UPDATE %s SET deleted=:deleted WHERE experiment_id IN (:ids)", ExperimentRunEnreplacedy.clreplaced.getSimpleName());
Query updateDeletedChildrenQuery = session.createQuery(updateDeletedChildren);
updateDeletedChildrenQuery.setParameter("deleted", true);
updateDeletedChildrenQuery.setParameter("ids", ids);
updateDeletedChildrenQuery.executeUpdate();
transaction.commit();
for (ExperimentEnreplacedy experimentEnreplacedy : experimentEnreplacedies) {
transaction = session.beginTransaction();
session.delete(experimentEnreplacedy);
transaction.commit();
}
}
return new ReconcileResult();
}
19
Source : SoftDeleteExperimentRuns.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
protected ReconcileResult reconcile(Set<String> ids) {
LOGGER.debug("Reconciling experiment runs " + ids.toString());
deleteRoleBindings(ids);
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
String experimentRunQueryString = String.format("from %s where id in (:ids)", ExperimentRunEnreplacedy.clreplaced.getSimpleName());
Query<ExperimentRunEnreplacedy> experimentRunDeleteQuery = session.createQuery(experimentRunQueryString, ExperimentRunEnreplacedy.clreplaced);
experimentRunDeleteQuery.setParameter("ids", ids);
List<ExperimentRunEnreplacedy> experimentRunEnreplacedies = experimentRunDeleteQuery.list();
Transaction transaction = session.beginTransaction();
String delete = String.format("DELETE FROM %s WHERE enreplacedy_id IN (:ids)", CommentEnreplacedy.clreplaced.getSimpleName());
Query deleteQuery = session.createQuery(delete);
deleteQuery.setParameter("ids", ids);
deleteQuery.executeUpdate();
transaction.commit();
for (ExperimentRunEnreplacedy experimentRunEnreplacedy : experimentRunEnreplacedies) {
transaction = session.beginTransaction();
session.delete(experimentRunEnreplacedy);
transaction.commit();
}
}
return new ReconcileResult();
}
19
Source : MetadataDAORdbImpl.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
private List<LabelsMappingEnreplacedy> getLabelsMappingEnreplacedies(Session session, IdentificationType id) {
Query<LabelsMappingEnreplacedy> query = session.createQuery(GET_LABELS_HQL + " ORDER BY lm.id.label", LabelsMappingEnreplacedy.clreplaced);
query.setParameter("enreplacedyHash", getEnreplacedyHash(id));
query.setParameter("enreplacedyType", id.getIdTypeValue());
return query.list();
}
19
Source : MetadataDAORdbImpl.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
public List<KeyValueStringProperty> getKeyValueProperties(GetKeyValuePropertiesRequest request) {
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
List<KeyValueStringProperty> keyValues = new ArrayList<>();
if (request.getGetAll()) {
Query<KeyValuePropertyMappingEnreplacedy> query = session.createQuery(GET_KEY_VALUE_PROPERTY_HQL, KeyValuePropertyMappingEnreplacedy.clreplaced);
query.setParameter(ModelDBConstants.ENreplacedY_HASH, getEnreplacedyHash(request.getId()));
query.setParameter(ModelDBConstants.PROPERTY_NAME, request.getPropertyName());
List<KeyValuePropertyMappingEnreplacedy> kvMappings = query.list();
if (!kvMappings.isEmpty()) {
kvMappings.forEach(mappingEnreplacedy -> {
keyValues.add(KeyValueStringProperty.newBuilder().setKey(mappingEnreplacedy.getId().getKey()).setValue(mappingEnreplacedy.getValue()).build());
});
}
} else {
for (String key : request.getKeysList()) {
KeyValuePropertyMappingEnreplacedy.KeyValuePropertyMappingId id0 = KeyValuePropertyMappingEnreplacedy.createId(request.getId(), key, request.getPropertyName());
KeyValuePropertyMappingEnreplacedy kvEnreplacedy = session.get(KeyValuePropertyMappingEnreplacedy.clreplaced, id0);
if (kvEnreplacedy != null) {
keyValues.add(KeyValueStringProperty.newBuilder().setKey(key).setValue(kvEnreplacedy.getValue()).build());
}
}
}
return keyValues;
}
}
19
Source : CleanUpEntitiesCron.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
private void cleanProjects(Session session) {
LOGGER.trace("Project cleaning");
String alias = "pr";
String deleteProjectsQueryString = new StringBuilder("FROM ").append(ProjectEnreplacedy.clreplaced.getSimpleName()).append(" ").append(alias).append(" WHERE ").append(alias).append(".").append(ModelDBConstants.CREATED).append(" = :created ").append(" AND ").append(alias).append(".").append(ModelDBConstants.DATE_CREATED).append(" < :created_date ").toString();
// Time less then a minute because possible to have create project request running when cron job
// running
// 5 minute lesser time
long time = Calendar.getInstance().getTimeInMillis() - 300000;
Query projectDeleteQuery = session.createQuery(deleteProjectsQueryString);
projectDeleteQuery.setParameter("created", false);
projectDeleteQuery.setParameter("created_date", time);
projectDeleteQuery.setMaxResults(this.recordUpdateLimit);
List<ProjectEnreplacedy> projectEnreplacedies = projectDeleteQuery.list();
List<String> projectIds = new ArrayList<>();
if (!projectEnreplacedies.isEmpty()) {
for (ProjectEnreplacedy projectEnreplacedy : projectEnreplacedies) {
projectIds.add(projectEnreplacedy.getId());
}
try {
roleService.deleteEnreplacedyResourcesWithServiceUser(projectIds, ModelDBResourceEnum.ModelDBServiceResourceTypes.PROJECT);
for (ProjectEnreplacedy projectEnreplacedy : projectEnreplacedies) {
try {
Transaction transaction = session.beginTransaction();
session.delete(projectEnreplacedy);
transaction.commit();
} catch (OptimisticLockException ex) {
LOGGER.info("CleanUpEnreplacediesCron : cleanProjects : Exception: {}", ex.getMessage());
}
}
} catch (OptimisticLockException ex) {
LOGGER.info("CleanUpEnreplacediesCron : cleanProjects : Exception: {}", ex.getMessage());
} catch (Exception ex) {
LOGGER.warn("CleanUpEnreplacediesCron : cleanProjects : Exception: ", ex);
}
}
LOGGER.debug("Project cleaned successfully : Cleaned projects count {}", projectIds.size());
}
19
Source : AuditLogsCron.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
/**
* The action to be performed by this timer task.
*/
@Override
public void run() {
LOGGER.info("AuditLogsCron wakeup");
CommonUtils.registeredBackgroundUtilsCount();
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
String alias = "al";
String getAuditLogsLocalQueryString = new StringBuilder("FROM ").append(AuditLogLocalEnreplacedy.clreplaced.getSimpleName()).append(" ").append(alias).toString();
Query getAuditLogsLocalQuery = session.createQuery(getAuditLogsLocalQueryString);
getAuditLogsLocalQuery.setMaxResults(this.recordUpdateLimit);
List<AuditLogLocalEnreplacedy> auditLogLocalEnreplacedies = getAuditLogsLocalQuery.list();
LOGGER.info("AuditLogsCron : Getting AuditLogLocalEnreplacedy count: {}", auditLogLocalEnreplacedies.size());
if (!auditLogLocalEnreplacedies.isEmpty()) {
Map<String, AuditLogLocalEnreplacedy> auditLogLocalEnreplacedyMap = auditLogLocalEnreplacedies.stream().collect(Collectors.toMap(AuditLogLocalEnreplacedy::getLocalId, auditLogLocalEnreplacedy -> auditLogLocalEnreplacedy));
List<BatchResponseRow> batchResponseRows = sendAuditLogsToUAC(true, auditLogLocalEnreplacedies);
if (!batchResponseRows.isEmpty()) {
deleteLocalAuditLogs(session, batchResponseRows, auditLogLocalEnreplacedyMap);
}
}
} catch (Exception ex) {
if (ex instanceof StatusRuntimeException) {
StatusRuntimeException exception = (StatusRuntimeException) ex;
if (exception.getStatus().getCode().value() == Code.PERMISSION_DENIED_VALUE) {
LOGGER.warn("AuditLogsCron Exception: {}", ex.getMessage());
} else {
LOGGER.warn("AuditLogsCron Exception: ", ex);
}
} else {
LOGGER.warn("AuditLogsCron Exception: ", ex);
}
} finally {
CommonUtils.unregisteredBackgroundUtilsCount();
}
LOGGER.info("AuditLogsCron finish tasks and reschedule");
}
19
Source : HibernateStatisticsCounterDao.java
with Mozilla Public License 2.0
from secdec
with Mozilla Public License 2.0
from secdec
@Override
public List<Map<String, Object>> getRawFindingTotalMap() {
String hql = "select new map (" + "count(*) as total, " + "counter.scanId as scanId) " + "from StatisticsCounter counter ";
hql += "group by counter.scanId";
Query query = getSession().createQuery(hql);
Object idsMap = query.list();
return (List<Map<String, Object>>) idsMap;
}
19
Source : Server.java
with MIT License
from pokiuwu
with MIT License
from pokiuwu
public void initCashShop() {
cashShop = new CashShop();
try (Session session = DatabaseManager.getSession()) {
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("FROM CashShopCategory");
List<CashShopCategory> categories = query.list();
categories.sort(Comparator.comparingInt(CashShopCategory::getIdx));
cashShop.setCategories(new ArrayList<>(categories));
query = session.createQuery("FROM CashShopItem");
List<CashShopItem> items = query.list();
items.forEach(item -> cashShop.addItem(item));
transaction.commit();
}
}
19
Source : UnmodifiableHibernateDao.java
with GNU General Public License v2.0
from ia-toki
with GNU General Public License v2.0
from ia-toki
@Override
public List<M> selectAll(FilterOptions<M> filterOptions, SelectionOptions selectionOptions) {
// MySQL doesn't support empty IN() clause
for (Collection<?> collection : filterOptions.getColumnsIn().values()) {
if (collection.isEmpty()) {
return Collections.emptyList();
}
}
CriteriaBuilder cb = currentSession().getCriteriaBuilder();
CriteriaQuery<M> cq = criteriaQuery();
Root<M> root = cq.from(getEnreplacedyClreplaced());
applyFilters(cb, cq, root, filterOptions);
List<Order> orders = Lists.newArrayList();
if (selectionOptions.getOrderDir() == OrderDir.ASC) {
orders.add(cb.asc(root.get(selectionOptions.getOrderBy())));
} else {
orders.add(cb.desc(root.get(selectionOptions.getOrderBy())));
}
if (selectionOptions.getOrderDir2().orElse(selectionOptions.getOrderDir()) == OrderDir.ASC) {
orders.add(cb.asc(root.get(selectionOptions.getOrderBy2())));
} else {
orders.add(cb.desc(root.get(selectionOptions.getOrderBy2())));
}
cq.orderBy(orders);
Query<M> query = currentSession().createQuery(cq);
if (selectionOptions.getPageSize() > 0) {
query.setFirstResult((selectionOptions.getPage() - 1) * selectionOptions.getPageSize());
query.setMaxResults(selectionOptions.getPageSize());
}
return query.list();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* 投影查询
*/
@Test
public void demo5() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("SELECT cust_name,cust_id FROM Customer ");
List list = query.list();
System.out.println(list);
// 在实体类中编写构造方法,构造方法参数为你需要查询的属性
Query query1 = session.createQuery("SELECT new Customer (cust_name) from Customer ");
List list1 = query1.list();
System.out.println(list1);
tx.commit();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* Hql多表查询 内连接
*/
@Test
public void demo8() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("FROM Customer c inner join c.linkMans");
List<Object[]> list = query.list();
for (Object[] o : list) {
System.out.println(Arrays.toString(o));
}
System.out.println("--------------------------------");
// fetch 会将数据整合 迫切内连接
Query query1 = session.createQuery("select distinct c FROM Customer c inner join fetch c.linkMans");
List<Customer> list1 = query1.list();
for (Customer o : list1) {
System.out.println(o);
}
tx.commit();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* 分页查询
*/
@Test
public void demo6() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("FROM LinkMan ");
query.setFirstResult(0);
query.setMaxResults(10);
List list = query.list();
for (Object o : list) {
System.out.println(o);
}
tx.commit();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* 条件
*/
@Test
public void demo4() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer where cust_name = :cust_name ");
query.setParameter("cust_name", "ac");
List<Customer> customer1 = query.list();
for (Customer customer : customer1) {
System.out.println(customer);
}
tx.commit();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* 分组查询
*/
@Test
public void demo7() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("SELECT l.lkm_name, COUNT(*) FROM LinkMan as l GROUP BY l.customer");
List<Object[]> list = query.list();
for (Object[] o : list) {
System.out.println(Arrays.toString(o));
}
tx.commit();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* HQL 简单查询
*/
@Test
public void demo2() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query from_customer_ = session.createQuery("from Customer ");
List<Customer> list = from_customer_.list();
for (Customer customer : list) {
System.out.println(customer);
}
tx.commit();
}
19
Source : HqlTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
@Test
public void demo9() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("FROM Customer c left join c.linkMans");
List<Object[]> list = query.list();
for (Object[] o : list) {
System.out.println(Arrays.toString(o));
}
tx.commit();
}
19
Source : CustomerTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
@Test
public void hibernateUtilsTest() {
Session hibernateSession = HibernateUtils.getHibernateSession();
Transaction transaction = hibernateSession.beginTransaction();
Customer customer = new Customer();
customer.setCust_name("hibernateUtilsTest测试数据");
Serializable save = hibernateSession.save(customer);
Customer customer1 = hibernateSession.get(Customer.clreplaced, 1L);
Customer load = hibernateSession.load(Customer.clreplaced, 1L);
customer1.setCust_name("testUpdateAAAA");
hibernateSession.update(customer1);
// hibernateSession.delete(customer1);
Query from_customer = hibernateSession.createQuery("from Customer");
List list = from_customer.list();
System.out.println(list);
transaction.commit();
// 资源释放
hibernateSession.close();
}
19
Source : CustomerTest.java
with Apache License 2.0
from huifer
with Apache License 2.0
from huifer
/**
* query
*/
@Test
public void query() {
Session session = HibernateUtils.getCurrentSession();
Transaction transaction = session.beginTransaction();
// 条件查询
Query query1 = session.createQuery("from Customer where cust_id>2 ");
List list = query1.list();
System.out.println(list.size());
query1 = session.createQuery("from Customer where cust_name like :cust_name");
query1.setParameter("cust_name", "a%");
list = query1.list();
System.out.println(list);
// 分页查询
query1 = session.createQuery("from Customer ");
// 设置分页
// 设置第几页
query1.setFirstResult(0);
// 每一页最多
query1.setMaxResults(3);
list = query1.list();
System.out.println(list);
transaction.commit();
}
19
Source : GeneratedSelectStatementsTests.java
with GNU Lesser General Public License v2.1
from GoogleCloudPlatform
with GNU Lesser General Public License v2.1
from GoogleCloudPlatform
@Test
public void limitOffsetClauseTest() {
openSessionAndDo(session -> {
Query q = session.createQuery("select s from SubTestEnreplacedy s").setFirstResult(8).setMaxResults(15);
q.list();
});
MockPreparedStatement statement = this.jdbcMockObjectFactory.getMockConnection().getPreparedStatementResultSetHandler().getPreparedStatements().get(0);
replacedertThat(statement.getSQL()).isEqualTo("select subtestent0_.id as id1_1_, subtestent0_.id1 as id2_1_, subtestent0_.id2 " + "as id3_1_ from SubTestEnreplacedy subtestent0_ limit ? offset ?");
replacedertThat(statement.getParameter(1)).isEqualTo(15);
replacedertThat(statement.getParameter(2)).isEqualTo(8);
}
19
Source : HibernateValidationResultStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<ValidationResult> getValidationResults(OrganisationUnit orgUnit, boolean includeOrgUnitDescendants, Collection<ValidationRule> validationRules, Collection<Period> periods) {
if (isEmpty(validationRules) || isEmpty(periods)) {
return new ArrayList<>();
}
String orgUnitFilter = orgUnit == null ? "" : "vr.organisationUnit.path like :orgUnitPath and ";
Query<ValidationResult> query = getQuery("from ValidationResult vr where " + orgUnitFilter + "vr.validationRule in :validationRules and vr.period in :periods ");
if (orgUnit != null) {
query.setParameter("orgUnitPath", orgUnit.getPath() + (includeOrgUnitDescendants ? "%" : ""));
}
query.setParameter("validationRules", validationRules);
query.setParameter("periods", periods);
return query.list();
}
19
Source : HibernateTrackedEntityProgramOwnerStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<TrackedEnreplacedyProgramOwner> getTrackedEnreplacedyProgramOwners(List<Long> teiIds) {
String hql = "from TrackedEnreplacedyProgramOwner tepo where tepo.enreplacedyInstance.id in (:teiIds)";
Query<TrackedEnreplacedyProgramOwner> q = getQuery(hql);
q.setParameterList("teiIds", teiIds);
return q.list();
}
19
Source : HibernateTrackedEntityProgramOwnerStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<TrackedEnreplacedyProgramOwner> getTrackedEnreplacedyProgramOwners(List<Long> teiIds, long programId) {
String hql = "from TrackedEnreplacedyProgramOwner tepo where tepo.enreplacedyInstance.id in (:teiIds) and tepo.program.id=(:programId) ";
Query<TrackedEnreplacedyProgramOwner> q = getQuery(hql);
q.setParameterList("teiIds", teiIds);
q.setParameter("programId", programId);
return q.list();
}
19
Source : HibernateTrackedEntityAttributeStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<Program, Set<TrackedEnreplacedyAttribute>> getTrackedEnreplacedyAttributesByProgram() {
Map<Program, Set<TrackedEnreplacedyAttribute>> result = new HashMap<>();
Query query = sessionFactory.getCurrentSession().createQuery("select p.programAttributes from Program p");
List<ProgramTrackedEnreplacedyAttribute> programTrackedEnreplacedyAttributes = query.list();
for (ProgramTrackedEnreplacedyAttribute programTrackedEnreplacedyAttribute : programTrackedEnreplacedyAttributes) {
if (!result.containsKey(programTrackedEnreplacedyAttribute.getProgram())) {
result.put(programTrackedEnreplacedyAttribute.getProgram(), Sets.newHashSet(programTrackedEnreplacedyAttribute.getAttribute()));
} else {
result.get(programTrackedEnreplacedyAttribute.getProgram()).add(programTrackedEnreplacedyAttribute.getAttribute());
}
}
return result;
}
19
Source : HibernateOrganisationUnitStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<OrganisationUnit> getOrganisationUnits(OrganisationUnitQueryParams params) {
SqlHelper hlp = new SqlHelper();
String hql = "select distinct o from OrganisationUnit o ";
if (params.isFetchChildren()) {
hql += "left join fetch o.children c ";
}
if (params.hasGroups()) {
hql += "join o.groups og ";
}
if (params.hasQuery()) {
hql += hlp.whereAnd() + " (lower(o.name) like :queryLower or o.code = :query or o.uid = :query) ";
}
if (params.hasParents()) {
hql += hlp.whereAnd() + " (";
for (OrganisationUnit parent : params.getParents()) {
hql += "o.path like :" + parent.getUid() + " or ";
}
hql = TextUtils.removeLastOr(hql) + ") ";
}
if (params.hasGroups()) {
hql += hlp.whereAnd() + " og.id in (:groupIds) ";
}
if (params.hasLevels()) {
hql += hlp.whereAnd() + " o.hierarchyLevel in (:levels) ";
}
if (params.getMaxLevels() != null) {
hql += hlp.whereAnd() + " o.hierarchyLevel <= :maxLevels ";
}
hql += "order by o." + params.getOrderBy().getName();
Query<OrganisationUnit> query = getQuery(hql);
if (params.hasQuery()) {
query.setParameter("queryLower", "%" + params.getQuery().toLowerCase() + "%");
query.setParameter("query", params.getQuery());
}
if (params.hasParents()) {
for (OrganisationUnit parent : params.getParents()) {
query.setParameter(parent.getUid(), parent.getPath() + "%");
}
}
if (params.hasGroups()) {
query.setParameterList("groupIds", IdentifiableObjectUtils.getIdentifiers(params.getGroups()));
}
if (params.hasLevels()) {
query.setParameterList("levels", params.getLevels());
}
if (params.getMaxLevels() != null) {
query.setParameter("maxLevels", params.getMaxLevels());
}
if (params.getFirst() != null) {
query.setFirstResult(params.getFirst());
}
if (params.getMax() != null) {
query.setMaxResults(params.getMax()).list();
}
return query.list();
}
19
Source : HibernateKeyJsonValueStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<String> getKeysInNamespace(String namespace, Date lastUpdated) {
String hql = "select key from KeyJsonValue where namespace = :namespace";
if (lastUpdated != null) {
hql += " and lastupdated >= :lastUpdated ";
}
Query<String> query = getTypedQuery(hql);
query.setParameter("namespace", namespace);
if (lastUpdated != null) {
query.setParameter("lastUpdated", lastUpdated);
}
return query.list();
}
19
Source : HibernateKeyJsonValueStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<String> getNamespaces() {
String hql = "select distinct namespace from KeyJsonValue";
Query<String> query = getTypedQuery(hql);
return query.list();
}
19
Source : HibernateInterpretationStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
public List<Interpretation> getInterpretations(User user) {
String hql = "select distinct i from Interpretation i left join i.comments c " + "where i.user = :user or c.user = :user order by i.lastUpdated desc";
Query<Interpretation> query = getQuery(hql).setParameter("user", user).setCacheable(cacheable);
return query.list();
}
19
Source : HibernateInterpretationStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
public List<Interpretation> getInterpretations(User user, int first, int max) {
String hql = "select distinct i from Interpretation i left join i.comments c " + "where i.user = :user or c.user = :user order by i.lastUpdated desc";
Query<Interpretation> query = getQuery(hql).setParameter("user", user).setMaxResults(first).setMaxResults(max).setCacheable(cacheable);
return query.list();
}
19
Source : HibernateDeletedObjectStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
@Override
public List<DeletedObject> query(DeletedObjectQuery query) {
CriteriaBuilder builder = getCurrentSession().getCriteriaBuilder();
CriteriaQuery<DeletedObject> criteriaQuery = builder.createQuery(DeletedObject.clreplaced);
Root<DeletedObject> root = criteriaQuery.from(DeletedObject.clreplaced);
Predicate predicate = buildCriteria(builder, root, query);
criteriaQuery.select(root);
if (!predicate.getExpressions().isEmpty())
criteriaQuery.where(predicate);
Query<DeletedObject> typedQuery = getCurrentSession().createQuery(criteriaQuery);
if (!query.isSkipPaging()) {
Pager pager = query.getPager();
typedQuery.setFirstResult(pager.getOffset());
typedQuery.setMaxResults(pager.getPageSize());
}
return typedQuery.list();
}
19
Source : HibernateTest.java
with Apache License 2.0
from code4wt
with Apache License 2.0
from code4wt
@Test
public void testHQL() {
System.out.println("-----------------------------✨ HQL Query ✨+--------------------------");
Session session = null;
try {
session = buildSessionFactory.openSession();
String hql = "from Article where author = :author and create_time > :createTime";
Query query = session.createQuery(hql);
query.setParameter("author", "coolblog.xyz");
query.setParameter("createTime", "2018.06.10");
List<Article> articles = query.list();
System.out.println("HQL Query Result: ");
articles.forEach(System.out::println);
System.out.println();
} finally {
if (Objects.nonNull(session)) {
session.close();
}
}
}
18
Source : VersioningUtils.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
public static List<AttributeEnreplacedy> getAttributeEnreplacedies(Session session, Long repoId, String commitHash, List<String> locations, List<String> attributeKeys) {
StringBuilder getAttributesHQLBuilder = new StringBuilder("From AttributeEnreplacedy kv where kv.enreplacedy_hash = :enreplacedyHash " + " AND kv.enreplacedy_name = :enreplacedyName AND kv.field_type = :fieldType");
if (attributeKeys != null && !attributeKeys.isEmpty()) {
getAttributesHQLBuilder.append(" AND kv.key IN (:keys) ");
}
getAttributesHQLBuilder.append(" ORDER BY kv.id");
Query getQuery = session.createQuery(getAttributesHQLBuilder.toString());
getQuery.setParameter("enreplacedyName", ModelDBConstants.BLOB);
getQuery.setParameter("enreplacedyHash", getVersioningCompositeId(repoId, commitHash, locations));
getQuery.setParameter("fieldType", ModelDBConstants.ATTRIBUTES);
if (attributeKeys != null && !attributeKeys.isEmpty()) {
getQuery.setParameterList("keys", attributeKeys);
}
return getQuery.list();
}
18
Source : ArtifactPathMigrationUtils.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
public static void migration(Map<String, Object> propertiesMap) {
LOGGER.debug("Artifact path migration start");
Map<String, Object> artifactStoreConfigMap = (Map<String, Object>) propertiesMap.get(ModelDBConstants.ARTIFACT_STORE_CONFIG);
String artifactStoreType = (String) artifactStoreConfigMap.get(ModelDBConstants.ARTIFACT_STORE_TYPE);
String storeTypePathPrefix = null;
if (artifactStoreType.equals(ModelDBConstants.S3)) {
Map<String, Object> s3ConfigMap = (Map<String, Object>) artifactStoreConfigMap.get(ModelDBConstants.S3);
String cloudBucketName = (String) s3ConfigMap.get(ModelDBConstants.CLOUD_BUCKET_NAME);
LOGGER.trace("S3 cloud bucket name {}", cloudBucketName);
storeTypePathPrefix = "s3://" + cloudBucketName + ModelDBConstants.PATH_DELIMITER;
} else if (artifactStoreType.equals(ModelDBConstants.NFS)) {
Map<String, Object> nfsConfigMap = (Map<String, Object>) artifactStoreConfigMap.get(ModelDBConstants.NFS);
String rootDir = (String) nfsConfigMap.get(ModelDBConstants.NFS_ROOT_PATH);
LOGGER.trace("NFS server root path {}", rootDir);
storeTypePathPrefix = "nfs://" + rootDir + ModelDBConstants.PATH_DELIMITER;
}
Long count = getArtifactEnreplacedyCount();
int lowerBound = 0;
final int pagesize = 500;
LOGGER.debug("Total artifactEnreplacedies {}", count);
while (lowerBound < count) {
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
Transaction transaction = session.beginTransaction();
String queryString = "FROM ArtifactEnreplacedy ae WHERE ae." + ModelDBConstants.STORE_TYPE_PATH + " IS NULL ORDER BY ae.id asc";
Query query = session.createQuery(queryString);
query.setFirstResult(lowerBound);
query.setMaxResults(pagesize);
List<ArtifactEnreplacedy> artifactEnreplacedies = query.list();
for (ArtifactEnreplacedy artifactEnreplacedy : artifactEnreplacedies) {
if (!artifactEnreplacedy.getPath_only()) {
String storeTypePath = storeTypePathPrefix + artifactEnreplacedy.getPath();
artifactEnreplacedy.setStore_type_path(storeTypePath);
session.update(artifactEnreplacedy);
}
}
LOGGER.debug("finished processing page lower boundary {}", lowerBound);
transaction.commit();
lowerBound += pagesize;
}
}
LOGGER.debug("Artifact path migration stop");
}
18
Source : SoftDeleteExperimentRuns.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
private void deleteRoleBindings(Set<String> ids) {
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
String deleteExperimentRunQueryString = String.format("FROM %s WHERE id IN (:ids)", ExperimentRunEnreplacedy.clreplaced.getSimpleName());
Query<ExperimentRunEnreplacedy> experimentRunDeleteQuery = session.createQuery(deleteExperimentRunQueryString, ExperimentRunEnreplacedy.clreplaced);
experimentRunDeleteQuery.setParameter("ids", ids);
List<ExperimentRunEnreplacedy> experimentRunEnreplacedies = experimentRunDeleteQuery.list();
List<String> roleBindingNames = new LinkedList<>();
for (ExperimentRunEnreplacedy enreplacedy : experimentRunEnreplacedies) {
String ownerRoleBindingName = roleService.buildRoleBindingName(ModelDBConstants.ROLE_EXPERIMENT_RUN_OWNER, enreplacedy.getId(), enreplacedy.getOwner(), ModelDBResourceEnum.ModelDBServiceResourceTypes.EXPERIMENT_RUN.name());
if (ownerRoleBindingName != null) {
roleBindingNames.add(ownerRoleBindingName);
}
}
if (!roleBindingNames.isEmpty()) {
roleService.deleteRoleBindings(roleBindingNames);
}
}
}
18
Source : MetadataDAORdbImpl.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
public List<IdentificationType> getLabelIds(List<String> labels, OperatorEnum.Operator operator) {
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
Map<String, Object> parametersMap = new HashMap<>();
StringBuilder queryBuilder = new StringBuilder(GET_LABEL_IDS_HQL);
for (int index = 0; index < labels.size(); index++) {
if (operator.equals(OperatorEnum.Operator.CONTAIN) || operator.equals(OperatorEnum.Operator.NOT_CONTAIN)) {
queryBuilder.append(" lower(lm.id.").append(ModelDBConstants.LABEL).append(") ");
} else {
queryBuilder.append(" lm.id.").append(ModelDBConstants.LABEL);
}
RdbmsUtils.setValueWithOperatorInQuery(index, queryBuilder, operator, labels.get(index), parametersMap);
if (index < labels.size() - 1) {
queryBuilder.append(" AND ");
}
}
queryBuilder.append(" ORDER BY lm.id.label ");
Query<LabelsMappingEnreplacedy> query = session.createQuery(queryBuilder.toString(), LabelsMappingEnreplacedy.clreplaced);
RdbmsUtils.setParameterInQuery(query, parametersMap);
List<LabelsMappingEnreplacedy> labelsMappingEnreplacedies = query.list();
return labelsMappingEnreplacedies.stream().map(labelsMappingEnreplacedy -> {
IdentificationType.Builder builder = IdentificationType.newBuilder().setIdType(IDTypeEnum.IDType.forNumber(labelsMappingEnreplacedy.getId().getEnreplacedy_type()));
switch(builder.getIdType()) {
case VERSIONING_REPOSITORY:
builder.setIntId(Long.parseLong(labelsMappingEnreplacedy.getId().getEnreplacedy_hash()));
case VERSIONING_COMMIT:
default:
builder.setStringId(labelsMappingEnreplacedy.getId().getEnreplacedy_hash());
}
return builder.build();
}).collect(Collectors.toList());
} catch (Exception ex) {
if (ModelDBUtils.needToRetry(ex)) {
return getLabelIds(labels, operator);
} else {
throw ex;
}
}
}
18
Source : CleanUpEntitiesCron.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
private void cleanRepositories(Session session) {
LOGGER.trace("Repository cleaning");
String alias = "r";
String deleteRepositoriesQueryString = new StringBuilder("FROM ").append(RepositoryEnreplacedy.clreplaced.getSimpleName()).append(" ").append(alias).append(" WHERE ").append(alias).append(".").append(ModelDBConstants.CREATED).append(" = :created ").append(" AND ").append(alias).append(".").append(ModelDBConstants.DATE_CREATED).append(" < :created_date ").toString();
// Time less then a minute because possible to have create project request running when cron job
// running
// 5 minute lesser time
long time = Calendar.getInstance().getTimeInMillis() - 300000;
Query repositoryDeleteQuery = session.createQuery(deleteRepositoriesQueryString);
repositoryDeleteQuery.setParameter("created", false);
repositoryDeleteQuery.setParameter("created_date", time);
repositoryDeleteQuery.setMaxResults(this.recordUpdateLimit);
List<RepositoryEnreplacedy> repositoryEnreplacedies = repositoryDeleteQuery.list();
Map<String, RepositoryEnreplacedy> repositoryEnreplacedyMap = new HashMap<>();
Map<String, RepositoryEnreplacedy> datasetEnreplacedyMap = new HashMap<>();
if (!repositoryEnreplacedies.isEmpty()) {
for (RepositoryEnreplacedy repositoryEnreplacedy : repositoryEnreplacedies) {
if (repositoryEnreplacedy.isDataset()) {
datasetEnreplacedyMap.put(String.valueOf(repositoryEnreplacedy.getId()), repositoryEnreplacedy);
} else {
repositoryEnreplacedyMap.put(String.valueOf(repositoryEnreplacedy.getId()), repositoryEnreplacedy);
}
}
cleanUpEnreplacedyBasedOnResourceType(session, repositoryEnreplacedies, repositoryEnreplacedyMap, ModelDBResourceEnum.ModelDBServiceResourceTypes.REPOSITORY);
cleanUpEnreplacedyBasedOnResourceType(session, repositoryEnreplacedies, datasetEnreplacedyMap, ModelDBResourceEnum.ModelDBServiceResourceTypes.DATASET);
}
LOGGER.debug("Repository cleaned successfully : Cleaned repositories count {}", repositoryEnreplacedyMap.size());
LOGGER.debug("Dataset cleaned successfully : Cleaned datasets count {}", datasetEnreplacedyMap.size());
}
18
Source : CommentDAORdbImpl.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
@Override
public List<Comment> getComments(String enreplacedyType, String enreplacedyId) {
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
Query query = session.createQuery(GET_ENreplacedY_COMMENT_QUERY);
query.setParameter("enreplacedyId", enreplacedyId);
query.setParameter("enreplacedyName", enreplacedyType);
List<UserCommentEnreplacedy> userCommentEnreplacedies = query.list();
if (userCommentEnreplacedies == null) {
return new ArrayList<>();
}
LOGGER.debug("Got {} comments", userCommentEnreplacedies.size());
return RdbmsUtils.convertUserCommentListFromUserComments(userCommentEnreplacedies);
} catch (Exception ex) {
if (ModelDBUtils.needToRetry(ex)) {
return getComments(enreplacedyType, enreplacedyId);
} else {
throw ex;
}
}
}
18
Source : PopulateVersionMigration.java
with Apache License 2.0
from VertaAI
with Apache License 2.0
from VertaAI
private static void migrateVersionOfDatasetVersions() {
LOGGER.debug("DatasetVersion version migration started");
Long count;
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
String repoCountQueryStr = "SELECT COUNT(r) FROM " + RepositoryEnreplacedy.clreplaced.getSimpleName() + " r " + "WHERE r.deleted = false AND r.datasetRepositoryMappingEnreplacedy IS NOT EMPTY ";
Query repoCountQuery = session.createQuery(repoCountQueryStr);
count = (Long) repoCountQuery.getSingleResult();
}
int lowerBound = 0;
final int pagesize = recordUpdateLimit;
LOGGER.debug("Total Datasets {}", count);
while (lowerBound < count) {
try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
LOGGER.debug("starting DatasetVersion version migration");
String repoQuery = "SELECT r FROM " + RepositoryEnreplacedy.clreplaced.getSimpleName() + " r " + "WHERE r.deleted = false AND r.datasetRepositoryMappingEnreplacedy IS NOT EMPTY " + "ORDER BY r.date_created";
Query repoTypedQuery = session.createQuery(repoQuery);
repoTypedQuery.setFirstResult(lowerBound);
repoTypedQuery.setMaxResults(pagesize);
List<RepositoryEnreplacedy> datasetEnreplacedies = repoTypedQuery.list();
LOGGER.debug("got datasets");
if (datasetEnreplacedies.size() > 0) {
Set<Long> datasetIds = new HashSet<>();
for (RepositoryEnreplacedy datasetsEnreplacedy : datasetEnreplacedies) {
datasetIds.add(datasetsEnreplacedy.getId());
}
datasetEnreplacedies.clear();
for (Long datasetId : datasetIds) {
String commitCountQueryStr = "SELECT count(c) FROM " + CommitEnreplacedy.clreplaced.getSimpleName() + " c " + "INNER JOIN c.repository r WHERE r.id = :datasetId AND c.parent_commits IS NOT EMPTY ";
Query commitCountQuery = session.createQuery(commitCountQueryStr);
commitCountQuery.setParameter("datasetId", datasetId);
Long commitCount = (Long) commitCountQuery.getSingleResult();
int commitLowerBound = 0;
final int commitPagesize = recordUpdateLimit;
LOGGER.debug("Total DatasetVersions {}", commitCount);
long version = 0L;
while (commitLowerBound < commitCount) {
String commitQuery = "SELECT c FROM " + CommitEnreplacedy.clreplaced.getSimpleName() + " c " + "INNER JOIN c.repository r WHERE r.id = :datasetId AND c.parent_commits IS NOT EMPTY " + "ORDER BY c.date_created";
Query commitTypedQuery = session.createQuery(commitQuery);
commitTypedQuery.setParameter("datasetId", datasetId);
commitTypedQuery.setFirstResult(commitLowerBound);
commitTypedQuery.setMaxResults(commitPagesize);
List<CommitEnreplacedy> commitEnreplacedies = commitTypedQuery.list();
Transaction transaction = session.beginTransaction();
try {
for (CommitEnreplacedy commitEnreplacedy : commitEnreplacedies) {
List<String> location = Collections.singletonList(ModelDBConstants.DEFAULT_VERSIONING_BLOB_LOCATION);
String compositeId = VersioningUtils.getVersioningCompositeId(datasetId, commitEnreplacedy.getCommit_hash(), location);
version = version + 1;
metadataDAO.addProperty(session, IdentificationType.newBuilder().setIdType(IDTypeEnum.IDType.VERSIONING_REPO_COMMIT_BLOB).setStringId(compositeId).build(), ModelDBConstants.VERSION, String.valueOf(version));
}
LOGGER.debug("All datasetVersion's version are migrated for the Dataset '{}' ", datasetId);
} finally {
transaction.commit();
}
commitLowerBound += commitPagesize;
}
}
} else {
LOGGER.debug("Datasets total count 0");
}
lowerBound += pagesize;
} catch (Exception ex) {
if (ModelDBUtils.needToRetry(ex)) {
migrateVersionOfDatasetVersions();
} else {
throw ex;
}
} finally {
LOGGER.debug("gc starts");
Runtime.getRuntime().gc();
LOGGER.debug("gc ends");
}
}
LOGGER.debug("DatasetVersion version migration finished");
}
18
Source : HibernateStatisticsCounterDao.java
with Mozilla Public License 2.0
from secdec
with Mozilla Public License 2.0
from secdec
@Override
public List<Map<String, Object>> getFindingSeverityMap(List<Integer> filteredSeverities, List<Integer> filteredVulnerabilities, Map<String, Object> queryParamsMap, List<String> ignoreVulnsSubqueries, Scan scan) {
String hql = "select new map (" + "count(*) as total, " + "counter.scanId as scanId, " + "counter.currentGenericSeverityId as genericSeverityId) " + "from StatisticsCounter counter ";
List<String> whereStatements = getWhereStatements(filteredSeverities, filteredVulnerabilities, ignoreVulnsSubqueries, scan);
if (!whereStatements.isEmpty()) {
hql += "where ";
hql += CollectionUtils.join(" and ", whereStatements);
}
hql += "group by counter.scanId, counter.currentGenericSeverityId";
Query query = getSession().createQuery(hql);
addParameterLists(filteredSeverities, filteredVulnerabilities, scan, query);
for (Map.Entry<String, Object> entry : queryParamsMap.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
Object idsMap = query.list();
return (List<Map<String, Object>>) idsMap;
}
18
Source : HibernateDao.java
with Apache License 2.0
from RyanSusana
with Apache License 2.0
from RyanSusana
@Override
public List<T> find(com.elepy.dao.Query query) {
try (Session session = sessionFactory.openSession()) {
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery = cb.createQuery(getType());
final Root<T> root = criteriaQuery.from(getType());
Predicate predicate = new HibernateQueryFactory<>(schema, root, cb).generatePredicate(query.getExpression());
final List<Order> orders = generateOrderBy(cb, root, query);
Query<T> qry = session.createQuery(criteriaQuery.select(root).where(predicate).orderBy(orders)).setFirstResult(query.getSkip()).setMaxResults(query.getLimit());
return loadLazyCollections(qry.list());
}
}
18
Source : DatabaseManager.java
with MIT License
from pokiuwu
with MIT License
from pokiuwu
/**
* Sends a simple query to the DB to ensure that the connection stays alive.
*/
private static void sendHeartBeat() {
Session session = getSession();
Transaction t = session.beginTransaction();
Query q = session.createQuery("from Char where id = 1");
q.list();
t.commit();
session.close();
EventManager.addEvent(DatabaseManager::sendHeartBeat, KEEP_ALIVE_MS);
}
18
Source : Nomad.java
with GNU Affero General Public License v3.0
from GHzGangster
with GNU Affero General Public License v3.0
from GHzGangster
public void test() {
Session session = null;
try {
int clanId = 1;
boolean isLeader = true;
session = DB.getSession();
session.beginTransaction();
Query<Clan> query = session.createQuery("from Clan c join fetch c.members m join fetch m.character where c.id = :clan", Clan.clreplaced);
query.setParameter("clan", clanId);
Clan clan = query.uniqueResult();
if (clan != null && isLeader) {
// Hibernate.initialize(clan.getApplications());
Query<MessageClanApplication> queryM = session.createQuery("from MessageClanApplication m join fetch m.character where m.clan = :clan", MessageClanApplication.clreplaced);
queryM.setParameter("clan", clan);
clan.setApplications(queryM.list());
}
if (isLeader) {
logger.debug("{} applications (2).", clan.getApplications().size());
}
session.getTransaction().commit();
DB.closeSession(session);
} catch (Exception e) {
logger.error("Exception occurred!", e);
DB.rollbackAndClose(session);
}
logger.debug("DONE!");
}
18
Source : SwiftDaoImpl.java
with Apache License 2.0
from fanruan
with Apache License 2.0
from fanruan
@Override
public List<?> select(String hql, QueryProcessor queryProcessor) {
try (Session session = sessionFactory.openSession()) {
Query query = session.createQuery(hql);
if (queryProcessor != null) {
queryProcessor.process(query);
}
return query.list();
}
}
18
Source : HibernateOptionStore.java
with BSD 3-Clause "New" or "Revised" License
from dhis2
with BSD 3-Clause "New" or "Revised" License
from dhis2
// -------------------------------------------------------------------------
// Implementation methods
// -------------------------------------------------------------------------
@Override
public List<Option> getOptions(long optionSetId, String key, Integer max) {
String hql = "select option from OptionSet as optionset " + "join optionset.options as option where optionset.id = :optionSetId ";
if (key != null) {
hql += "and lower(option.name) like lower('%" + key + "%') ";
}
hql += "order by index(option)";
Query<Option> query = getQuery(hql);
query.setParameter("optionSetId", optionSetId);
if (max != null) {
query.setMaxResults(max);
}
return query.list();
}
See More Examples