use of javax.persistence.TypedQuery in project dataverse by IQSS.
the class DatasetVersionServiceBean method findByFriendlyVersionNumber.
public DatasetVersion findByFriendlyVersionNumber(Long datasetId, String friendlyVersionNumber) {
// FIXME: this logic doesn't work
Long majorVersionNumber = null;
Long minorVersionNumber = null;
String[] versions = friendlyVersionNumber.split("\\.");
try {
if (versions.length == 1) {
majorVersionNumber = Long.parseLong(versions[0]);
} else if (versions.length == 2) {
majorVersionNumber = Long.parseLong(versions[0]);
minorVersionNumber = Long.parseLong(versions[1]);
} else {
return null;
}
} catch (NumberFormatException n) {
return null;
}
if (minorVersionNumber != null) {
String queryStr = "SELECT v from DatasetVersion v where v.dataset.id = :datasetId and v.versionNumber= :majorVersionNumber and v.minorVersionNumber= :minorVersionNumber";
DatasetVersion foundDatasetVersion = null;
try {
Query query = em.createQuery(queryStr);
query.setParameter("datasetId", datasetId);
query.setParameter("majorVersionNumber", majorVersionNumber);
query.setParameter("minorVersionNumber", minorVersionNumber);
foundDatasetVersion = (DatasetVersion) query.getSingleResult();
} catch (javax.persistence.NoResultException e) {
logger.warning("no ds version found: " + datasetId + " " + friendlyVersionNumber);
// DO nothing, just return null.
}
return foundDatasetVersion;
}
if (majorVersionNumber == null && minorVersionNumber == null) {
return null;
}
if (majorVersionNumber != null && minorVersionNumber == null) {
try {
TypedQuery<DatasetVersion> typedQuery = em.createQuery("SELECT v from DatasetVersion v where v.dataset.id = :datasetId and v.versionNumber= :majorVersionNumber", DatasetVersion.class);
typedQuery.setParameter("datasetId", datasetId);
typedQuery.setParameter("majorVersionNumber", majorVersionNumber);
DatasetVersion retVal = null;
List<DatasetVersion> versionsList = typedQuery.getResultList();
for (DatasetVersion dsvTest : versionsList) {
if (retVal == null) {
retVal = dsvTest;
} else {
if (retVal.getMinorVersionNumber().intValue() < dsvTest.getMinorVersionNumber().intValue()) {
retVal = dsvTest;
}
}
}
return retVal;
} catch (javax.persistence.NoResultException e) {
logger.warning("no ds version found: " + datasetId + " " + friendlyVersionNumber);
// DO nothing, just return null.
}
}
return null;
}
use of javax.persistence.TypedQuery in project deltaspike by apache.
the class QueryCriteria method createQuery.
@Override
public TypedQuery<R> createQuery() {
try {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<R> query = createCriteriaQuery(builder);
From<C, C> root = query.from(entityClass);
if (selections.size() == 1) {
Selection<?>[] selections = prepareSelections(query, builder, root);
query.select((Selection<? extends R>) selections[0]);
}
if (selections.size() > 1) {
query.multiselect(prepareSelections(query, builder, root));
}
List<Predicate> predicates = predicates(builder, root);
query.distinct(distinct);
if (!predicates.isEmpty()) {
query.where(predicates.toArray(new Predicate[predicates.size()]));
}
applyProcessors(query, builder, root);
return (TypedQuery<R>) entityManager.createQuery(query);
} catch (RuntimeException e) {
log.log(Level.SEVERE, "Exception while creating JPA query", e);
throw e;
}
}
use of javax.persistence.TypedQuery in project mycore by MyCoRe-Org.
the class MCRIView2Commands method fixDeadEntries.
@MCRCommand(syntax = "fix dead tile jobs", help = "Deletes entries for files which dont exist anymore!")
public static void fixDeadEntries() {
EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
List<MCRTileJob> tiles = allTileJobQuery.getResultList();
tiles.stream().filter(tj -> {
MCRPath path = MCRPath.getPath(tj.getDerivate(), tj.getPath());
return !Files.exists(path);
}).peek(tj -> LOGGER.info("Delete TileJob {}:{}", tj.getDerivate(), tj.getPath())).forEach(em::remove);
}
use of javax.persistence.TypedQuery in project openremote by openremote.
the class ManagerIdentityProvider method getUsersFromDb.
static User[] getUsersFromDb(PersistenceService persistenceService, UserQuery query) {
StringBuilder sb = new StringBuilder();
List<Object> parameters = new ArrayList<>();
final UserQuery userQuery = query != null ? query : new UserQuery();
// BUILD SELECT
sb.append("SELECT u");
// BUILD FROM
sb.append(" FROM User u");
if (userQuery.assetPredicate != null || userQuery.pathPredicate != null) {
sb.append(" join UserAssetLink ua on ua.id.userId = u.id");
}
// BUILD WHERE
sb.append(" WHERE 1=1");
if (userQuery.tenantPredicate != null && !TextUtil.isNullOrEmpty(userQuery.tenantPredicate.realm)) {
sb.append(" AND u.realm = ?").append(parameters.size() + 1);
parameters.add(userQuery.tenantPredicate.realm);
}
if (userQuery.assetPredicate != null) {
sb.append(" AND ua.id.assetId = ?").append(parameters.size() + 1);
parameters.add(userQuery.assetPredicate.id);
}
if (userQuery.pathPredicate != null) {
sb.append(" AND ?").append(parameters.size() + 1).append(" <@ get_asset_tree_path(ua.asset_id)");
parameters.add(userQuery.pathPredicate.path);
}
if (userQuery.ids != null && userQuery.ids.length > 0) {
sb.append(" AND u.id IN (?").append(parameters.size() + 1);
parameters.add(userQuery.ids[0]);
for (int i = 1; i < userQuery.ids.length; i++) {
sb.append(",?").append(parameters.size() + 1);
parameters.add(userQuery.ids[i]);
}
sb.append(")");
}
if (userQuery.usernames != null && userQuery.usernames.length > 0) {
sb.append(" and (");
boolean isFirst = true;
for (StringPredicate pred : userQuery.usernames) {
if (!isFirst) {
sb.append(" or ");
}
isFirst = false;
final int pos = parameters.size() + 1;
// No case support for username
sb.append("upper(u.username)");
sb.append(buildMatchFilter(pred, pos));
parameters.add(pred.prepareValue());
}
sb.append(")");
}
if (userQuery.select != null && userQuery.select.excludeRegularUsers) {
sb.append(" and u.secret IS NOT NULL");
} else if (userQuery.select != null && userQuery.select.excludeServiceUsers) {
sb.append(" and u.secret IS NULL");
}
// BUILD ORDER BY
if (userQuery.orderBy != null) {
if (userQuery.orderBy.property != null) {
sb.append(" ORDER BY");
switch(userQuery.orderBy.property) {
case CREATED_ON:
sb.append(" u.createdOn");
break;
case FIRST_NAME:
sb.append(" u.firstName");
break;
case LAST_NAME:
sb.append(" u.lastName");
break;
case USERNAME:
// Remove service user prefix
sb.append(" replace(u.username, '").append(User.SERVICE_ACCOUNT_PREFIX).append("', '')");
break;
case EMAIL:
sb.append(" u.email");
break;
default:
throw new UnsupportedOperationException("Unsupported order by value: " + userQuery.orderBy.property);
}
if (userQuery.orderBy.descending) {
sb.append(" DESC");
}
}
}
List<User> users = persistenceService.doReturningTransaction(entityManager -> {
TypedQuery<User> sqlQuery = entityManager.createQuery(sb.toString(), User.class);
IntStream.range(0, parameters.size()).forEach(i -> sqlQuery.setParameter(i + 1, parameters.get(i)));
if (userQuery.limit != null && userQuery.limit > 0) {
sqlQuery.setMaxResults(userQuery.limit);
}
if (userQuery.offset != null && userQuery.offset > 0) {
sqlQuery.setFirstResult(query.offset);
}
return sqlQuery.getResultList();
});
if (userQuery.select != null && (userQuery.select.basic || userQuery.select.excludeSystemUsers)) {
// TODO: Move this within the query
return users.stream().filter(user -> {
boolean keep = !userQuery.select.excludeSystemUsers || !user.isSystemAccount();
if (keep && userQuery.select.basic) {
// Clear out data and leave only basic info
user.setAttributes(null);
user.setEmail(null);
user.setRealmId(null);
user.setSecret(null);
}
return keep;
}).toArray(User[]::new);
}
return users.toArray(new User[0]);
}
use of javax.persistence.TypedQuery in project dataverse by IQSS.
the class OAIRecordServiceBean method findOAIRecordBySetNameandGlobalId.
public OAIRecord findOAIRecordBySetNameandGlobalId(String setName, String globalId) {
OAIRecord oaiRecord = null;
String queryString = "SELECT object(h) from OAIRecord h where h.globalId = :globalId";
// and h.setName is null";
queryString += setName != null ? " and h.setName = :setName" : "";
logger.fine("findOAIRecordBySetNameandGlobalId; query: " + queryString + "; globalId: " + globalId + "; setName: " + setName);
TypedQuery query = em.createQuery(queryString, OAIRecord.class).setParameter("globalId", globalId);
if (setName != null) {
query.setParameter("setName", setName);
}
try {
oaiRecord = (OAIRecord) query.setMaxResults(1).getSingleResult();
} catch (javax.persistence.NoResultException e) {
// Do nothing, just return null.
}
logger.fine("returning oai record.");
return oaiRecord;
}
Aggregations