本文整理了Java中javax.jdo.Query
类的一些代码示例,展示了Query
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query
类的具体详情如下:
包路径:javax.jdo.Query
类名称:Query
[英]The Query
interface allows applications to obtain persistent instances, values, and aggregate data from the data store. The PersistenceManager is the factory for Query
instances. There may be many Query
instances associated with a PersistenceManager
. Multiple queries might be executed simultaneously by different threads, but the implementation might choose to execute them serially. In either case, the implementation must be thread-safe.
There are three required elements in a Query
: the class of the results, the candidate collection of instances, and the filter.
There are optional elements: parameter declarations, variable declarations, import statements, ordering and grouping specifications, result and result class, the range of results, and flags indicating whether the query result is unique and whether the query can be modified.
The query namespace is modeled after methods in Java:
setClass
corresponds to the class definitiondeclareParameters
corresponds to formal parameters of a methoddeclareVariables
corresponds to local variables of a methodsetFilter
and setOrdering
correspond to the method bodyThere are two namespaces in queries. Type names have their own namespace that is separate from the namespace for fields, variables and parameters.
The method setClass
introduces the name of the candidate class in the type namespace. The method declareImports
introduces the names of the imported class or interface types in the type namespace. Imported type names must be unique. When used (e.g. in a parameter declaration, cast expression, etc.) a type name must be the name of the candidate class, the name of a class or interface imported by method declareImports
, or denote a class or interface from the same package as the candidate class.
The method setClass
introduces the names of the candidate class fields.
The method declareParameters
introduces the names of the parameters. A name introduced by declareParameters
hides the name of a candidate class field of the same name. Parameter names must be unique.
The method declareVariables
introduces the names of the variables. A name introduced by declareVariables
hides the name of a candidate class field if equal. Variable names must be unique and must not conflict with parameter names.
The result of the query by default is a list of result class instances, but might be specified via setResult
. The class of the result by default is the candidate class, but might be specified via setResultClass
.
A hidden field may be accessed using the 'this' qualifier: this.fieldName
.
The Query
interface provides methods which execute the query based on the parameters given. They return a single instance or a List
of result class instances which the user can iterate to get results. The signature of the execute
methods specifies that they return an Object
which must be cast to the appropriate result by the user.
Any parameters passed to the execute
methods are used only for this execution, and are not remembered for future execution.
[中]Query
接口允许应用程序从数据存储中获取持久实例、值和聚合数据。PersistenceManager是Query
实例的工厂。可能有许多Query
实例与PersistenceManager
关联。多个查询可能由不同的线程同时执行,但实现可能会选择串行执行它们。无论哪种情况,实现都必须是线程安全的。Query
中有三个必需元素:结果类、候选实例集合和过滤器。
有可选元素:参数声明、变量声明、导入语句、排序和分组规范、结果和结果类、结果范围,以及指示查询结果是否唯一以及是否可以修改查询的标志。
查询名称空间是按照Java中的方法建模的:
*setClass
对应于类定义
*declareParameters
对应于方法的形式参数
*declareVariables
对应于方法的局部变量
*setFilter
和setOrdering
对应于方法体
查询中有两个名称空间。类型名称有自己的名称空间,与字段、变量和参数的名称空间不同。
方法setClass
在类型名称空间中引入候选类的名称。方法declareImports
在类型名称空间中引入导入的类或接口类型的名称。导入的类型名称必须是唯一的。使用时(例如,在参数声明、强制转换表达式等中),类型名必须是候选类的名称、通过方法declareImports
导入的类或接口的名称,或表示与候选类来自同一包的类或接口。
方法setClass
引入候选类字段的名称。
方法declareParameters
引入了参数的名称。declareParameters
引入的名称隐藏了同名候选类字段的名称。参数名称必须是唯一的。
方法declareVariables
引入变量的名称。declareVariables
引入的名称会隐藏候选类字段的名称(如果相等)。变量名必须唯一,且不得与参数名冲突。
默认情况下,查询的结果是结果类实例的列表,但可以通过setResult
指定。默认情况下,结果的类是候选类,但可以通过setResultClass
指定。
可以使用“this”限定符[20$]访问隐藏字段。Query
接口提供了基于给定参数执行查询的方法。它们返回单个实例或List
个结果类实例,用户可以通过迭代获得结果。execute
方法的签名指定它们返回一个Object
,用户必须将其转换为适当的结果。
传递给execute
方法的任何参数仅用于此执行,不会在将来执行时记住。
代码示例来源:origin: apache/hive
private boolean poolHasChildren(MWMResourcePlan resourcePlan, String poolPath) {
boolean commited = false;
Query query = null;
try {
openTransaction();
query = pm.newQuery(MWMPool.class, "resourcePlan == rp && path.startsWith(poolPath)");
query.declareParameters("MWMResourcePlan rp, java.lang.String poolPath");
query.setResult("count(this)");
query.setUnique(true);
Long count = (Long) query.execute(resourcePlan, poolPath + ".");
commited = commitTransaction();
return count != null && count > 0;
} finally {
rollbackAndCleanup(commited, query);
}
}
代码示例来源:origin: apache/hive
Map<String, Object> params = new HashMap<>();
String queryFilterString = makeQueryFilterString(catName, dbName, null, filter, params);
query = pm.newQuery(MTable.class);
query.declareImports("import java.lang.String");
query.setResult("tableName");
query.setResultClass(java.lang.String.class);
if (maxTables >= 0) {
query.setRange(0, maxTables);
query.declareParameters(parameterDeclaration);
query.setFilter(queryFilterString);
Collection<String> names = (Collection<String>)query.executeWithMap(params);
代码示例来源:origin: apache/hive
private List<MPartition> listMPartitions(String catName, String dbName, String tableName,
int max, QueryWrapper queryWrapper) {
boolean success = false;
List<MPartition> mparts = null;
try {
openTransaction();
LOG.debug("Executing listMPartitions");
dbName = normalizeIdentifier(dbName);
tableName = normalizeIdentifier(tableName);
Query query = queryWrapper.query = pm.newQuery(MPartition.class,
"table.tableName == t1 && table.database.name == t2 && table.database.catalogName == t3");
query.declareParameters("java.lang.String t1, java.lang.String t2, java.lang.String t3");
query.setOrdering("partitionName ascending");
if (max >= 0) {
query.setRange(0, max);
}
mparts = (List<MPartition>) query.execute(tableName, dbName, catName);
LOG.debug("Done executing query for listMPartitions");
pm.retrieveAll(mparts);
success = commitTransaction();
LOG.debug("Done retrieving all objects for listMPartitions {}", mparts);
} finally {
if (!success) {
rollbackTransaction();
}
}
return mparts;
}
代码示例来源:origin: apache/hive
private MDelegationToken getTokenFrom(String tokenId) {
Query query = pm.newQuery(MDelegationToken.class, "tokenIdentifier == tokenId");
query.declareParameters("java.lang.String tokenId");
query.setUnique(true);
MDelegationToken delegationToken = (MDelegationToken) query.execute(tokenId);
if (query != null) {
query.closeAll();
}
return delegationToken;
}
代码示例来源:origin: apache/hive
private Query createActivePlanQuery() {
openTransaction();
Query query = pm.newQuery(MWMResourcePlan.class, "status == activeStatus && ns == nsname");
query.declareParameters("java.lang.String activeStatus, java.lang.String nsname");
query.setUnique(true);
return query;
}
代码示例来源:origin: org.codehaus.redback/redback-users-jdo
@SuppressWarnings("unchecked")
private List<User> findUsers( String searchField, String searchKey, boolean ascendingUsername )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Extent extent = pm.getExtent( JdoUser.class, true );
Query query = pm.newQuery( extent );
String ordering = ascendingUsername ? "username ascending" : "username descending";
query.setOrdering( ordering );
query.declareImports( "import java.lang.String" );
query.declareParameters( "String searchKey" );
query.setFilter( "this." + searchField + ".toLowerCase().indexOf(searchKey.toLowerCase()) > -1" );
List<User> result = (List<User>) query.execute( searchKey );
result = (List<User>) pm.detachCopyAll( result );
tx.commit();
return result;
}
finally
{
rollback( tx );
}
}
代码示例来源:origin: apache/hive
@SuppressWarnings("unchecked")
public List<MRoleMap> listMRoleMembers(String roleName) {
boolean success = false;
Query query = null;
List<MRoleMap> mRoleMemeberList = new ArrayList<>();
try {
LOG.debug("Executing listRoleMembers");
openTransaction();
query = pm.newQuery(MRoleMap.class, "role.roleName == t1");
query.declareParameters("java.lang.String t1");
query.setUnique(false);
List<MRoleMap> mRoles = (List<MRoleMap>) query.execute(roleName);
pm.retrieveAll(mRoles);
success = commitTransaction();
mRoleMemeberList.addAll(mRoles);
LOG.debug("Done retrieving all objects for listRoleMembers");
} finally {
rollbackAndCleanup(success, query);
}
return mRoleMemeberList;
}
代码示例来源:origin: apache/hive
query = pm.newQuery(MTableColumnStatistics.class);
String filter;
String parameters;
query.setFilter(filter);
query.declareParameters(parameters);
if (colName != null) {
query.setUnique(true);
mStatsObj =
(MTableColumnStatistics) query.executeWithArray(normalizeIdentifier(tableName),
normalizeIdentifier(dbName),
normalizeIdentifier(catName),
normalizeIdentifier(colName));
pm.retrieve(mStatsObj);
pm.deletePersistent(mStatsObj);
} else {
throw new NoSuchObjectException("Column stats doesn't exist for db=" + dbName + " table="
(List<MTableColumnStatistics>) query.execute(
normalizeIdentifier(tableName),
normalizeIdentifier(dbName),
代码示例来源:origin: apache/sentry
/**
* Get the MAuthzPathsMapping object from authzObj
*/
private MAuthzPathsMapping getMAuthzPathsMappingCore(PersistenceManager pm,
long authzSnapshotID, String authzObj) {
Query query = pm.newQuery(MAuthzPathsMapping.class);
query.setFilter("this.authzSnapshotID == authzSnapshotID && this.authzObjName == authzObjName");
query.declareParameters("long authzSnapshotID, java.lang.String authzObjName");
query.setUnique(true);
return (MAuthzPathsMapping) query.execute(authzSnapshotID, authzObj);
}
代码示例来源:origin: org.apache.maven.continuum/continuum-store
public List<BuildResult> getAllBuildsForAProjectByDate( int projectId )
{
PersistenceManager pm = getPersistenceManager();
Transaction tx = pm.currentTransaction();
try
{
tx.begin();
Query query = pm.newQuery( "SELECT FROM " + BuildResult.class.getName() +
" WHERE project.id == projectId PARAMETERS int projectId ORDER BY endTime DESC" );
query.declareImports( "import java.lang.Integer" );
query.declareParameters( "Integer projectId" );
List result = (List) query.execute( new Integer( projectId ) );
result = (List) pm.detachCopyAll( result );
tx.commit();
return result;
}
finally
{
rollback( tx );
}
}
代码示例来源:origin: apache/hive
String dbName = normalizeIdentifier(schemaName.getDbName());
String catName = normalizeIdentifier(schemaName.getCatName());
query = pm.newQuery(MSchemaVersion.class,
"iSchema.name == schemaName && iSchema.db.name == dbName && iSchema.db.catalogName == cat");
query.declareParameters("java.lang.String schemaName, java.lang.String dbName, " +
"java.lang.String cat");
query.setUnique(true);
query.setOrdering("version descending");
query.setRange(0, 1);
MSchemaVersion mSchemaVersion = (MSchemaVersion)query.execute(name, dbName, catName);
pm.retrieve(mSchemaVersion);
if (mSchemaVersion != null) {
pm.retrieveAll(mSchemaVersion.getCols());
if (mSchemaVersion.getSerDe() != null) {
pm.retrieve(mSchemaVersion.getSerDe());
代码示例来源:origin: apache/hive
lowered_tbl_names.add(normalizeIdentifier(t));
query = pm.newQuery(MTable.class);
query.setFilter("database.name == db && database.catalogName == cat && tbl_names.contains(tableName)");
query.declareParameters("java.lang.String db, java.lang.String cat, java.util.Collection tbl_names");
Collection mtables = (Collection) query.execute(db, catName, lowered_tbl_names);
if (mtables == null || mtables.isEmpty()) {
dbExistsQuery = pm.newQuery(MDatabase.class, "name == db && catalogName == cat");
dbExistsQuery.declareParameters("java.lang.String db, java.lang.String cat");
dbExistsQuery.setUnique(true);
dbExistsQuery.setResult("name");
String dbNameIfExists = (String) dbExistsQuery.execute(db, catName);
if (org.apache.commons.lang.StringUtils.isEmpty(dbNameIfExists)) {
throw new UnknownDBException("Could not find database " +
rollbackAndCleanup(committed, query);
if (dbExistsQuery != null) {
dbExistsQuery.closeAll();
代码示例来源:origin: apache/hive
query = pm.newQuery("select constraintName from org.apache.hadoop.hive.metastore.model.MConstraint where "
+ "((parentTable.tableName == ptblname && parentTable.database.name == pdbname && " +
"parentTable.database.catalogName == pcatname) || "
"childTable.database.name == cdbname && childTable.database.catalogName == ccatname)) " +
(constraintname != null ? " && constraintName == constraintname" : ""));
query.declareParameters("java.lang.String ptblname, java.lang.String pdbname,"
+ "java.lang.String pcatname, java.lang.String ctblname, java.lang.String cdbname," +
"java.lang.String ccatname" +
constraintname != null ?
((Collection<?>) query.
executeWithArray(tableName, dbName, catName, tableName, dbName, catName, constraintname)):
((Collection<?>) query.
executeWithArray(tableName, dbName, catName, tableName, dbName, catName));
for (Iterator<?> i = constraintNamesColl.iterator(); i.hasNext();) {
String currName = (String) i.next();
constraintNames.add(currName);
query = pm.newQuery(MConstraint.class);
query.setFilter("param.contains(constraintName)");
query.declareParameters("java.util.Collection param");
Collection<?> constraints = (Collection<?>)query.execute(constraintNames);
mConstraints = new ArrayList<>();
for (Iterator<?> i = constraints.iterator(); i.hasNext();) {
query.closeAll();
代码示例来源:origin: apache/hive
Query query = pm.newQuery(
"select partitionName from org.apache.hadoop.hive.metastore.model.MPartition "
+ "where " + queryFilterString);
query.setRange(0, maxParts);
query.declareParameters(parameterDeclaration);
if (ascending) {
query.setOrdering("partitionName ascending");
} else {
query.setOrdering("partitionName descending");
query.setResult("partitionName");
Collection<String> names = (Collection<String>) query.executeWithMap(params);
partNames = new ArrayList<String>(names);
success = commitTransaction();
LOG.debug("Done retrieving all objects for getPartitionNamesByFilter, size: {}", partNames.size());
query.closeAll();
} finally {
if (!success) {
代码示例来源:origin: apache/hive
return null;
Query query = pm.newQuery(MPartition.class, jdoFilter);
if (maxParts >= 0) {
query.setRange(0, maxParts);
query.declareParameters(parameterDeclaration);
query.setOrdering("partitionName ascending");
@SuppressWarnings("unchecked")
List<MPartition> mparts = (List<MPartition>) query.executeWithMap(params);
LOG.debug("Done executing query for getPartitionsViaOrmFilter");
pm.retrieveAll(mparts); // TODO: why is this inconsistent with what we get by names?
LOG.debug("Done retrieving all objects for getPartitionsViaOrmFilter");
List<Partition> results = convertToParts(mparts);
query.closeAll();
return results;
代码示例来源:origin: apache/hive
private List<RuntimeStat> getMRuntimeStats(int maxEntries, int maxCreateTime) {
Query<MRuntimeStat> query = pm.newQuery(MRuntimeStat.class);
query.setOrdering("createTime descending");
if (maxCreateTime > 0) {
query.setFilter("createTime < "+maxCreateTime);
}
if (maxEntries < 0) {
maxEntries = Integer.MAX_VALUE;
}
List<RuntimeStat> ret = new ArrayList<>();
List<MRuntimeStat> res = (List<MRuntimeStat>) query.execute();
int totalEntries = 0;
for (MRuntimeStat mRuntimeStat : res) {
pm.retrieve(mRuntimeStat);
totalEntries += mRuntimeStat.getWeight();
ret.add(MRuntimeStat.toThrift(mRuntimeStat));
if (totalEntries >= maxEntries) {
break;
}
}
return ret;
}
代码示例来源:origin: apache/hive
private MSchemaVersion getMSchemaVersion(String catName, String dbName, String schemaName, int version) {
Query query = null;
try {
dbName = normalizeIdentifier(dbName);
schemaName = normalizeIdentifier(schemaName);
query = pm.newQuery(MSchemaVersion.class,
"iSchema.name == schemaName && iSchema.db.name == dbName &&" +
"iSchema.db.catalogName == cat && version == schemaVersion");
query.declareParameters( "java.lang.String schemaName, java.lang.String dbName," +
"java.lang.String cat, java.lang.Integer schemaVersion");
query.setUnique(true);
MSchemaVersion mSchemaVersion =
(MSchemaVersion)query.executeWithArray(schemaName, dbName, catName, version);
pm.retrieve(mSchemaVersion);
if (mSchemaVersion != null) {
pm.retrieveAll(mSchemaVersion.getCols());
if (mSchemaVersion.getSerDe() != null) {
pm.retrieve(mSchemaVersion.getSerDe());
}
}
return mSchemaVersion;
} finally {
if (query != null) {
query.closeAll();
}
}
}
代码示例来源:origin: apache/hive
Query query = queryWrapper.query = pm.newQuery(MPartition.class);
query.setFilter(filter);
query.declareParameters(makeParameterDeclarationString(params));
if (max_parts >= 0) {
query.setRange(0, max_parts);
query.setResult(resultsCol);
return (Collection) query.executeWithMap(params);
代码示例来源:origin: apache/hive
query = pm.newQuery(MNotificationLog.class, filterBuilder.toString());
query.declareParameters(parameterBuilder.toString());
query.setOrdering("eventId ascending");
int maxEventResponse = MetastoreConf.getIntVar(conf, ConfVars.METASTORE_MAX_EVENT_RESPONSE);
int maxEvents = (rqst.getMaxEvents() < maxEventResponse && rqst.getMaxEvents() > 0) ? rqst.getMaxEvents() : maxEventResponse;
query.setRange(0, maxEvents);
Collection<MNotificationLog> events =
(Collection) query.executeWithArray(parameterVals.toArray(new Object[parameterVals.size()]));
commited = commitTransaction();
if (events == null) {
代码示例来源:origin: apache/hive
LOG.warn("The table does not have the same column definition as its partition.");
Query query = queryWrapper.query = pm.newQuery(MPartitionColumnStatistics.class);
String paramStr = "java.lang.String t1, java.lang.String t2, java.lang.String t3";
String filter = "tableName == t1 && dbName == t2 && catName == t3 && (";
query.setFilter(filter);
query.declareParameters(paramStr);
query.setOrdering("partitionName ascending");
@SuppressWarnings("unchecked")
List<MPartitionColumnStatistics> result =
(List<MPartitionColumnStatistics>) query.executeWithArray(params);
pm.retrieveAll(result);
committed = commitTransaction();
return result;
内容来源于网络,如有侵权,请联系作者删除!