Skip Headers

# Basic DatabaseQuery Read Operations

Previous

Next

Example: A Simple ReadAllQuery illustrates a simple read query. It uses a TopLink expression, but does not use its own arguments for the query. Instead, it relies on the search parameters the expression provides. This example builds the expression within its code, but does not register the query with the session.

A Simple ReadAllQuery

    // This example returns a Vector of employees whose employee ID is > 100

    // Initialize the DatabaseQuery by specifying the query type
    // and set the reference class for the query
    ReadAllQuery query = new ReadAllQuery(Employee.class);

    // Retrieve ExpressionBuilder from the query
    ExpressionBuilder builder = query.getExpressionBuilder();

    /* Configure the query execution. Because this example uses an expression, it uses the setSelectionCriteria method */
    query.setSelectionCriteria(builder.get("id").greaterThan(100));

    // Execute the query
    Vector employees = (Vector) session.executeQuery(query);

Example: A Named Read Query with Two Arguments illustrates a complex `readObject` query that uses all available configuration options.

A Named Read Query with Two Arguments

    // Initialize the DatabaseQuery by specifying the query type
    // and set the reference class for the query
    ReadObjectQuery query = new ReadObjectQuery(Employee.class);
    // Retrieve ExpressionBuilder from the query
    ExpressionBuilder builder = query.getExpressionBuilder();
    // Define two expressions that map to the first and last names of the employee
    Expression firstNameExpression = emp.get("firstName").equal(emp.getParameter("firstName"));
    Expression lastNameExpression = emp.get("lastName").equal(emp.getParameter("lastName"));

    /* Configure the query execution. Because this example uses an expression, it uses the setSelectionCriteria method */
    query.setSelectionCriteria(firstNameExpression.and(lastNameExpression));
    // Specify the required arguments for the query
    query.addArgument("firstName");
    query.addArgument("lastName");

    // Add the query to the session
    session.addQuery("getEmployeeWithName", query);

    /* Execute the query by referencing its name and providing values for the specified arguments */
    Employee employee = (Employee) session.executeQuery("getEmployeeWithName","Bob","Smith");