Generating JPA Criteria Queries in NetBeans
NetBeans can turn a Jakarta Persistence entity class into a starting point for a JPA Criteria Query, reducing hand-written boilerplate and keeping the query close to the model it queries. The generated source is useful in Java applications built with Maven or Gradle, especially where dynamic filters must be assembled at runtime.
The Criteria API expresses a query through objects such as CriteriaBuilder, CriteriaQuery and Root. Compared with a JPQL string, it gives the compiler more opportunities to catch mistakes and makes optional predicates easier to combine. It suits reporting screens, admin tools and multi-tenant back ends.
Generation still needs editorial judgement. NetBeans knows field names and Java types, but it does not know whether an empty string should match, whether a false flag matters, or which records a user may see. Treat the output as a reviewed scaffold rather than production logic.
For Australian developers, examples should reflect local data: GST registration, AUD amounts and personal information handled under the Privacy Act 1988 and Australian Privacy Principles. A team spread across Sydney, Melbourne and Brisbane can still share one persistence model, provided query conventions live in the repository.
Prepare a persistence project
Create or open a Java project with a Jakarta Persistence unit, then make sure the entity class is managed by that unit. Check persistence.xml, or the Maven or Gradle configuration, for the correct provider and database credentials. For an application serving Australian customers, a Boolean gstRegistered field and BigDecimal prices in AUD provide realistic filter targets.
Keep provider configuration out of source control and use environment variables or a local profile for secrets. A developer working from a Perth home office should also trust the local network before connecting to a shared database; this rogue DHCP detection script can identify unexpected address assignments that might expose the session.
Generate a query from an entity
In NetBeans, open the Projects window, right-click the entity and choose Generate JPA Criteria Query; the exact label can vary slightly between releases. Select a destination package with the other persistence helpers, and review the proposed fields so the first query remains narrow and easy to inspect. The generator uses entity metadata rather than live customer records.
A query works best when its purpose is concrete: find Australian customers by email and GST status, or list invoice lines for an AUD total. When a Melbourne developer steps away from the IDE for lunch, plant-based lunch ideas can provide a quick break, but the query itself should return records only after role and tenant checks.
Understand the generated criteria code
NetBeans normally creates an EntityManager-based method with CriteriaBuilder, CriteriaQuery, Root and one or more predicates. Confirm that imports use jakarta.persistence.criteria for a current Jakarta project; older javax.persistence projects need their matching package. A simple email filter has this shape:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Customer> query = builder.createQuery(Customer.class);
Root<Customer> customer = query.from(Customer.class);
query.select(customer).where(
builder.equal(
customer.get("email"),
builder.parameter(String.class, "email")
)
);
TypedQuery<Customer> typed = em.createQuery(query);
typed.setParameter("email", email);
The generated predicate tells NetBeans to build the select, from and where parts, but it cannot supply business context. Change literal values to parameters, preserve null as “no filter” and ensure a false Boolean still applies. If the persistence processor creates a Customer_ metamodel, prefer its typed attributes where the generated code and project conventions allow.
Build flexible filters safely
Optional search fields are where generated criteria code becomes more valuable. Collect active filters in a List<Predicate>, add each one only when it has a meaningful value, then pass the predicates to the query builder.
- Treat
emailas active only when it contains a non-blank value. - Preserve
gstRegisteredas false when the user selected it. - Map
statusto validated enum constants before comparison. - Bind an AUD
minimumAmountthreshold as a numeric parameter.
Result controls matter just as much as individual field filters:
- Apply
orderBybeforesetFirstResultandsetMaxResults. - Use a named parameter for every user-supplied value.
- Fetch related records only when the screen needs them.
- Keep tenant and role restrictions outside the optional filter block.
Never concatenate a customer value into JPQL or SQL to work around a type error. Criteria parameters are designed for safe binding, while an allow-listed choice still governs which field or sort direction can change.
Test criteria queries in NetBeans
Create a JUnit test beside the query class and run it from NetBeans. Use a small, deterministic dataset containing null fields, empty strings, false flags and duplicate sort keys. These cases expose the accidental filters that generated code often introduces.
Continuous integration can run the same NetBeans project on every push; the site's guide to NetBeans and Jenkins integration covers connecting those pieces. A Brisbane build agent and a Sydney developer can share results, but test data and clock-sensitive assertions should remain independent of each machine’s local time zone.
Keep entities and queries aligned
Entity models change as Australian businesses add fields, alter GST treatment or revise customer identifiers. NetBeans refactoring tools reduce the mechanical work: the Rename and Move refactoring guide shows how coordinated package and class changes can be applied across a project.
Regeneration will not safely repair every detail. Property names written as strings are not Java references, and a custom predicate, index hint or fetch strategy may be overwritten. Keep generated code in a separate query class, regenerate it after model changes and review the resulting diff before accepting it.
Use query results safely in production
Apply authorisation before returning customer records, and use a least-privileged database account for the application. When email, address or invoice details can reach logs, document retention and access controls consistent with the Privacy Act 1988 and applicable Australian Privacy Principles; legal review remains appropriate for the organisation’s particular data.
Measure the query with realistic cardinality. Add indexes based on actual predicates and execution plans, inspect N+1 fetching, and avoid loading full invoice histories for a list that shows only summaries. A production-ready query should have named parameters, deliberate null semantics, stable ordering, bounded results and a visible access rule, preserving the convenience of generated Criteria code while making its behaviour predictable for Australian users and support teams.