### Complete Example: Advanced Query Construction in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md A comprehensive example demonstrating multiple TorpedoQuery features combined: defining entities, performing inner joins, applying multiple conditions (AND, LIKE), grouping, ordering, and executing the query to select aggregated data. ```java // Define query Entity entity = from(Entity.class); SubEntity subEntity = innerJoin(entity.getSubEntities()); // Add conditions where(entity.isActive()).eq(true) .and(subEntity.getCode()).like().startsWith("ABC"); // Group and order groupBy(entity.getName()); orderBy(entity.getName()); // Create and execute the query Query query = select(entity.getName(), count(subEntity)); List results = query.list(entityManager); ``` -------------------------------- ### Executing Queries in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Shows how to execute a built TorpedoQuery using an `EntityManager`. It covers retrieving a single result using `get()` and a list of results using `list()`. ```java // Get a single result Entity result = query.get(entityManager); // Get a list of results List results = query.list(entityManager); ``` -------------------------------- ### Verify TorpedoQuery Installation with Java Code Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/installation.md This Java code snippet provides a basic test to verify if TorpedoQuery is installed correctly. It creates a simple entity, constructs a query using TorpedoQuery's static methods, and prints the resulting query string. This helps confirm that the library integrates properly with your project's build. ```java import static org.torpedoquery.jpa.Torpedo.*; // Your entity class public class MyEntity { private String name; // getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } } // Test code public class TorpedoQueryTest { public void testQuery() { MyEntity entity = from(MyEntity.class); Query query = select(entity); String queryString = query.getQuery(); System.out.println(queryString); // Should print: select myEntity_0 from MyEntity myEntity_0 } } ``` -------------------------------- ### Import Static Methods in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Imports the necessary static methods from the TorpedoQuery library for building queries. This is a prerequisite for using TorpedoQuery's DSL. ```java import static org.torpedoquery.jpa.Torpedo.*; ``` -------------------------------- ### Add TorpedoQuery Dependency to Gradle Project Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/installation.md This snippet demonstrates how to include the TorpedoQuery library in your Gradle project's build.gradle file. Replace '2.5.2' with the latest version found on Maven Central. ```groovy implementation 'org.torpedoquery:org.torpedoquery:2.5.2' ``` -------------------------------- ### Basic Select All Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Constructs and executes a basic query to retrieve all records from a specified entity. It involves defining the entity source, selecting the entity, and executing the list operation. ```java Entity entity = from(Entity.class); Query query = select(entity); List results = query.list(entityManager); ``` -------------------------------- ### Query with Simple WHERE Clause in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Adds a simple filtering condition to a query using the `where` clause. This example filters entities based on their name being equal to 'test'. ```java Entity entity = from(Entity.class); where(entity.getName()).eq("test"); Query query = select(entity); ``` -------------------------------- ### ORDER BY Clause Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Constructs a query that orders the results based on a specific field (`entity.getName()`). The results will be sorted in ascending order by default. ```java Entity entity = from(Entity.class); orderBy(entity.getName()); Query query = select(entity); ``` -------------------------------- ### Select Multiple Fields Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Constructs a query to select multiple specific fields from an entity, returning them as an array of objects. This allows for retrieving compound data efficiently. ```java Entity entity = from(Entity.class); Query query = select(entity.getName(), entity.getCode()); List results = query.list(entityManager); ``` -------------------------------- ### Add TorpedoQuery Dependency to Maven Project Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/installation.md This snippet shows how to add the TorpedoQuery library as a dependency in your Maven project's pom.xml file. Ensure you use the correct version available on Maven Central. ```xml org.torpedoquery org.torpedoquery 2.5.2 ``` -------------------------------- ### Dynamic Query Building with Conditional WHERE in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Illustrates dynamic query building where a `WHERE` clause is added only if a specific condition (e.g., user input is provided and not empty) is met. This allows for flexible query construction. ```java Entity entity = from(Entity.class); // Only add condition if value is provided String name = getUserInput(); if (name != null && !name.isEmpty()) { where(entity.getName()).eq(name); } Query query = select(entity); ``` -------------------------------- ### Basic INNER JOIN Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Constructs a query that includes an inner join with a related entity (`SubEntity`). It then selects fields from both the main entity and the joined entity. ```java Entity entity = from(Entity.class); SubEntity subEntity = innerJoin(entity.getSubEntity()); Query query = select(entity.getName(), subEntity.getCode()); ``` -------------------------------- ### Query with Multiple AND Conditions in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Combines multiple filtering conditions using the `and` operator. This query filters entities where the name is 'test' AND the code is 'ABC'. ```java Entity entity = from(Entity.class); where(entity.getName()).eq("test").and(entity.getCode()).eq("ABC"); Query query = select(entity); ``` -------------------------------- ### Query with Multiple OR Conditions in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Combines multiple filtering conditions using the `or` operator. This query filters entities where the name is 'test' OR the name is 'test2'. ```java Entity entity = from(Entity.class); where(entity.getName()).eq("test").or(entity.getName()).eq("test2"); Query query = select(entity); ``` -------------------------------- ### GROUP BY Clause Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Builds a query that groups results by a specific field (`entity.getName()`) and uses an aggregate function (`count()`) on the grouped results. It selects the grouping field and the count. ```java Entity entity = from(Entity.class); groupBy(entity.getName()); Query query = select(entity.getName(), count(entity)); ``` -------------------------------- ### Build and Install TorpedoQuery with Maven (Bash) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/contributing.md Builds and installs the TorpedoQuery project using Maven. This command cleans the project, compiles the source code, runs tests, and packages the artifacts. It's a crucial step after setting up the environment or pulling new changes. ```bash mvn clean install ``` -------------------------------- ### Select Specific Field Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Builds a query to retrieve only a specific field (e.g., name) from all records of an entity. This is useful for fetching targeted data without loading entire objects. ```java Entity entity = from(Entity.class); Query query = select(entity.getName()); List names = query.list(entityManager); ``` -------------------------------- ### Create Query Root - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Demonstrates how to start building a JPA query by specifying the entity using TorpedoQuery's fluent API. This method returns a proxy object to capture subsequent method calls for query construction. ```java Entity entity = from(Entity.class); ``` -------------------------------- ### Java Basic Query Example Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/api-reference.md Demonstrates the basic structure of creating and executing a query using the Torpedo Query library. It includes static imports, query creation with a simple condition, and execution against an EntityManager. ```java // Import static methods import static org.torpedoquery.jpa.Torpedo.*; import static org.torpedoquery.jpa.TorpedoFunction.*; // Create a query Entity entity = from(Entity.class); where(entity.getCode()).eq("test"); Query query = select(entity); // Execute the query EntityManager em = getEntityManager(); List results = query.list(em); ``` -------------------------------- ### Scalar Function COUNT Query in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/getting-started/quick-start.md Demonstrates the use of a scalar function, specifically `count()`, to aggregate results. This query counts the number of records in the `Entity` table. ```java Entity entity = from(Entity.class); Query query = select(count(entity)); ``` -------------------------------- ### Generate Sales Report with Aggregations (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/examples.md This Java example demonstrates how to generate a sales report by aggregating data across multiple entities like orders, order items, products, and customers. It uses TorpedoQuery to define complex filtering, grouping, ordering, and selection criteria. Dependencies include an EntityManager and the necessary domain classes (Order, OrderItem, Product, Customer, SalesReportEntry). ```java public class SalesReportingService { private final EntityManager entityManager; public SalesReportingService(EntityManager entityManager) { this.entityManager = entityManager; } public List generateSalesReport( LocalDate fromDate, LocalDate toDate, List productCategories, String region) { // Define main entities Order order = from(Order.class); OrderItem item = innerJoin(order.getItems()); Product product = innerJoin(item.getProduct()); Customer customer = innerJoin(order.getCustomer()); // Build where conditions where(order.getOrderDate()).between(fromDate, toDate); if (productCategories != null && !productCategories.isEmpty()) { where(product.getCategory()).in(productCategories); } if (region != null && !region.isEmpty()) { where(customer.getRegion()).eq(region); } // Group by product and month groupBy(product.getId(), product.getName(), product.getCategory()) .having(sum(item.getQuantity())).gt(0); // Order by product category and total revenue orderBy(product.getCategory(), desc(sum(operation(item.getQuantity()).multiply(item.getUnitPrice())))); // Select the report data Query query = select( product.getId(), product.getName(), product.getCategory(), sum(item.getQuantity()), sum(operation(item.getQuantity()).multiply(item.getUnitPrice())), avg(item.getUnitPrice()) ); // Execute the query List results = query.list(entityManager); // Map results to report entries return results.stream() .map(row -> new SalesReportEntry( (String) row[0], // productId (String) row[1], // productName (String) row[2], // category (Long) row[3], // totalQuantity (BigDecimal) row[4], // totalRevenue (BigDecimal) row[5] // avgPrice )) .collect(Collectors.toList()); } } ``` -------------------------------- ### Build Hierarchical Department Structure (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/examples.md This Java example demonstrates querying and structuring hierarchical data, specifically an organization's department hierarchy. It uses TorpedoQuery to fetch departments based on parent-child relationships and recursively builds a tree structure including employees within each department. Dependencies include an EntityManager and the relevant domain classes (Department, Employee, DepartmentDTO, EmployeeDTO). ```java public class OrganizationService { private final EntityManager entityManager; public OrganizationService(EntityManager entityManager) { this.entityManager = entityManager; } public List getDepartmentHierarchy(String topLevelDepartmentCode) { // Get the top-level department Department topDept = from(Department.class); where(topDept.getCode()).eq(topLevelDepartmentCode); Department topLevelDept = select(topDept).get(entityManager); // Build the hierarchy return buildDepartmentHierarchy(topLevelDept.getId()); } private List buildDepartmentHierarchy(String parentId) { // Get direct child departments Department dept = from(Department.class); where(dept.getParentId()).eq(parentId); orderBy(dept.getName()); List departments = select(dept).list(entityManager); // Transform to DTOs and recursively get children return departments.stream() .map(d -> { DepartmentDTO dto = new DepartmentDTO( d.getId(), d.getCode(), d.getName(), d.getLevel() ); // Get employees in this department Employee emp = from(Employee.class); where(emp.getDepartmentId()).eq(d.getId()); where(emp.getStatus()).eq(EmployeeStatus.ACTIVE); orderBy(emp.getLastName(), emp.getFirstName()); List employees = select(emp).list(entityManager); dto.setEmployees(employees.stream() .map(e -> new EmployeeDTO( e.getId(), e.getFirstName(), e.getLastName(), e.getPosition()) ) .collect(Collectors.toList())); // Recursively get child departments dto.setChildDepartments(buildDepartmentHierarchy(d.getId())); return dto; }) .collect(Collectors.toList()); } } ``` -------------------------------- ### User Search with Filtering and Pagination in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/examples.md Demonstrates building a complex user search query using TorpedoQuery in Java. It includes filtering by name, status, and creation date, along with sorting and pagination. Dependencies include JPA EntityManager and TorpedoQuery's query builder. ```java public class UserSearchService { private final EntityManager entityManager; public UserSearchService(EntityManager entityManager) { this.entityManager = entityManager; } public SearchResult searchUsers(UserSearchCriteria criteria) { User user = from(User.class); // Build search condition OnGoingLogicalCondition condition = condition(); // Search by name if (criteria.getName() != null && !criteria.getName().isEmpty()) { condition.and( condition(user.getFirstName()).like().any(criteria.getName()) .or(user.getLastName()).like().any(criteria.getName()) ); } // Filter by status if (criteria.getStatus() != null) { condition.and(user.getStatus()).eq(criteria.getStatus()); } // Filter by date range if (criteria.getCreatedFrom() != null) { condition.and(user.getCreatedDate()).gte(criteria.getCreatedFrom()); } if (criteria.getCreatedTo() != null) { condition.and(user.getCreatedDate()).lte(criteria.getCreatedTo()); } // Apply the condition if not empty if (!condition.isEmpty()) { where(condition); } // Apply sorting if ("nameAsc".equals(criteria.getSort())) { orderBy(user.getLastName(), user.getFirstName()); } else if ("nameDesc".equals(criteria.getSort())) { orderBy(desc(user.getLastName()), desc(user.getFirstName())); } else if ("dateAsc".equals(criteria.getSort())) { orderBy(user.getCreatedDate()); } else { // Default sort by creation date desc orderBy(desc(user.getCreatedDate())); } // Create the query Query query = select(user); // Count total results (for pagination) Query countQuery = select(count(user)); Long totalCount = countQuery.get(entityManager); // Execute paginated query javax.persistence.Query jpaQuery = entityManager.createQuery(query.getQuery()); // Apply parameters for (Map.Entry entry : query.getParameters().entrySet()) { jpaQuery.setParameter(entry.getKey(), entry.getValue()); } // Set pagination jpaQuery.setFirstResult(criteria.getPageNumber() * criteria.getPageSize()); jpaQuery.setMaxResults(criteria.getPageSize()); List results = jpaQuery.getResultList(); return new SearchResult<>(results, totalCount, criteria.getPageNumber(), criteria.getPageSize()); } } ``` -------------------------------- ### Java: Multi-Join Query with Complex Conditions using TorpedoQuery Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/examples.md Demonstrates building a complex query involving multiple chained joins (User -> City -> District -> State -> Country) with various conditions applied using 'WITH' clauses. It includes simple equality checks and complex OR conditions for filtering. This example highlights TorpedoQuery's ability to handle nested property access and intricate filtering logic. ```java public class ComplexQueryExample { private EntityManager manager; public List findUsers() { User from = from(User.class); City city = innerJoin(from.getCity()); with(city.getCode()).in("one", "two").or(city.getCode()).notIn("three", "four"); District district = innerJoin(city.getDistrict()); with(district.getCode()).notIn("exclude1", "exclude2"); State state = innerJoin(district.getState()); with(state.getCode()).eq("AP").or(state.getCode()).eq("GUJ").or(state.getCode()).eq("KTK"); with(state.getCountry().getCode()).eq("india"); return select(from).list(manager); } } ``` -------------------------------- ### Practical Example: Ordering Active Entities by Name and Date in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/orderby.md A complete example demonstrating how to filter entities for active ones and then order them alphabetically by name, with a secondary sort by creation date (newest first) for entities with the same name. ```java // Find all active entities ordered by name (A-Z) and creation date (newest first) Entity entity = from(Entity.class); where(entity.isActive()).eq(true); orderBy(asc(entity.getName()), desc(entity.getDateField())); Query query = select(entity); List results = query.list(entityManager); ``` -------------------------------- ### TorpedoQuery Example: Entities Above Average Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/subqueries.md A practical example showing how to find all entities whose integer field is greater than the average of all integer fields using a TorpedoQuery subquery. ```java Entity entity = from(Entity.class); Entity subSelect = from(Entity.class); where(entity.getIntegerField()).gt(select(avg(subSelect.getIntegerField()))); Query query = select(entity); ``` -------------------------------- ### TorpedoQuery: IN with Enumeration (Java) Source: https://github.com/xjodoin/torpedoquery/wiki/IN-query-condition Demonstrates using the IN condition with a direct enumeration of values. This is useful for specifying a fixed set of possible matches. No external libraries are required beyond TorpedoQuery. ```java Entity from = from(Entity.class); where(from.getCode()).in("Joe", "Bob"); Query select = select(from); ``` -------------------------------- ### Java Complex Query Example Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/api-reference.md Illustrates a more advanced query construction scenario involving inner joins, multiple conditions (like, startsWith), grouping, aggregation (count), having clauses, and ordering. It also shows selecting specific fields and aggregated results. ```java // Create entity proxies Entity entity = from(Entity.class); SubEntity subEntity = innerJoin(entity.getSubEntities()); // Add conditions where(entity.isActive()).eq(true) .and(subEntity.getCode()).like().startsWith("PREFIX_"); // Add grouping and aggregation groupBy(entity.getName()) .having(count(subEntity)).gt(5); // Add ordering orderBy(desc(count(subEntity)), entity.getName()); // Create and execute query Query query = select(entity.getName(), count(subEntity)); List results = query.list(entityManager); ``` -------------------------------- ### Java Dynamic Search Service with TorpedoQuery Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/examples.md A generic search service class in Java that utilizes TorpedoQuery to construct dynamic search queries. It supports filtering based on various criteria and applying sorting options. Dependencies include JPA's EntityManager and TorpedoQuery's query building functionalities. ```java public class GenericSearchService { private final EntityManager entityManager; private final Class entityClass; public GenericSearchService(EntityManager entityManager, Class entityClass) { this.entityManager = entityManager; this.entityClass = entityClass; } public List search(List criteria, List sortings, int maxResults) { T entity = from(entityClass); // Build the WHERE clause from generic criteria if (criteria != null && !criteria.isEmpty()) { OnGoingLogicalCondition mainCondition = condition(); for (SearchCriterion criterion : criteria) { applySearchCriterion(mainCondition, entity, criterion); } where(mainCondition); } // Apply sorting if (sortings != null && !sortings.isEmpty()) { List sortFields = new ArrayList<>(); for (SortCriterion sort : sortings) { // Use reflection to get the appropriate getter try { String getterName = "get" + StringUtils.capitalize(sort.getFieldName()); Method getterMethod = entityClass.getMethod(getterName); Object fieldValue = getterMethod.invoke(entity); if ("DESC".equalsIgnoreCase(sort.getDirection())) { sortFields.add(desc(fieldValue)); } else { sortFields.add(fieldValue); } } catch (Exception e) { // Log warning and continue logger.warn("Could not sort by field: " + sort.getFieldName(), e); } } if (!sortFields.isEmpty()) { orderBy(sortFields.toArray()); } } // Execute query with limit Query query = select(entity); javax.persistence.Query jpaQuery = entityManager.createQuery(query.getQuery()); // Apply parameters for (Map.Entry entry : query.getParameters().entrySet()) { jpaQuery.setParameter(entry.getKey(), entry.getValue()); } if (maxResults > 0) { jpaQuery.setMaxResults(maxResults); } return jpaQuery.getResultList(); } private void applySearchCriterion(OnGoingLogicalCondition condition, T entity, SearchCriterion criterion) { try { // Get the field value using reflection String getterName = "get" + StringUtils.capitalize(criterion.getFieldName()); Method getterMethod = entityClass.getMethod(getterName); Object fieldValue = getterMethod.invoke(entity); // Apply appropriate operator switch (criterion.getOperator()) { case EQUALS: condition.and(fieldValue).eq(criterion.getValue()); break; case LIKE: condition.and(fieldValue).like().any(criterion.getValue().toString()); break; case GREATER_THAN: condition.and(fieldValue).gt(criterion.getValue()); break; case LESS_THAN: condition.and(fieldValue).lt(criterion.getValue()); break; case IN: if (criterion.getValue() instanceof Collection) { condition.and(fieldValue).in((Collection) criterion.getValue()); } break; case IS_NULL: condition.and(fieldValue).isNull(); break; case IS_NOT_NULL: condition.and(fieldValue).isNotNull(); break; // Add other operators as needed } } catch (Exception e) { // Log warning and continue logger.warn("Could not apply criterion for field: " + criterion.getFieldName(), e); } } } ``` -------------------------------- ### Complete GROUP BY with HAVING and Related Entities in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/groupby.md This example shows a complete TorpedoQuery setup using GROUP BY with related entities and multiple HAVING conditions. It joins entities with sub-entities, applies WHERE clauses, and filters groups based on aggregated values and related fields. ```java // Define entities Entity entity = from(Entity.class); SubEntity subEntity = innerJoin(entity.getSubEntities()); // Add WHERE conditions where(entity.isActive()).eq(true); // Define GROUP BY with HAVING groupBy(entity.getName(), entity.getCode()) .having(sum(entity.getIntegerField())).gt(100) .and(subEntity.getNumberField()).isNotNull(); // Create the final query Query query = select( entity.getName(), entity.getCode(), sum(entity.getIntegerField()), avg(subEntity.getNumberField()) ); ``` -------------------------------- ### TorpedoQuery: IN with Collection (Java) Source: https://github.com/xjodoin/torpedoquery/wiki/IN-query-condition Shows how to use the IN condition with a Java List collection. This is ideal when the set of values to match against is dynamically generated or stored in a collection. Requires Java's ArrayList. ```java List codes = new ArrayList(); codes.add("Joe"); codes.add("Bob"); Entity from = from(Entity.class); where(from.getCode()).in(codes); Query select = select(from); ``` -------------------------------- ### Search Form Implementation in TorpedoQuery (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/dynamic-queries.md This example shows a robust implementation of a search form using TorpedoQuery. It dynamically builds a query based on search text, date ranges, and status filters, applying sorting options as specified. The method returns a list of 'Entity' objects matching the criteria. ```java public List search(SearchForm form) { Entity entity = from(Entity.class); // Start with an empty condition OnGoingLogicalCondition searchCondition = condition(); // Add text search if provided if (form.getSearchText() != null && !form.getSearchText().isEmpty()) { String searchPattern = "%" + form.getSearchText() + "%"; OnGoingLogicalCondition textSearch = condition(entity.getName()).like(searchPattern) .or(entity.getCode()).like(searchPattern); searchCondition.and(textSearch); } // Add date range if provided if (form.getStartDate() != null) { searchCondition.and(entity.getDateField()).gte(form.getStartDate()); } if (form.getEndDate() != null) { searchCondition.and(entity.getDateField()).lte(form.getEndDate()); } // Add status filter if provided if (form.getStatusList() != null && !form.getStatusList().isEmpty()) { searchCondition.and(entity.getStatus()).in(form.getStatusList()); } // Apply the condition if not empty if (!searchCondition.isEmpty()) { where(searchCondition); } // Add sorting if ("dateDesc".equals(form.getSortOption())) { orderBy(desc(entity.getDateField())); } else if ("dateAsc".equals(form.getSortOption())) { orderBy(asc(entity.getDateField())); } else if ("nameAsc".equals(form.getSortOption())) { orderBy(asc(entity.getName())); } else { // Default sorting orderBy(desc(entity.getDateField())); } // Create and execute the query Query query = select(entity); return query.list(entityManager); } ``` -------------------------------- ### Java: Complex Data Filtering with Geographic Proximity using TorpedoQuery Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/examples.md Demonstrates complex filtering of properties based on various criteria including price range, property types, amenities, location, and geographic proximity. It uses JPA's EntityManager and a LocationService for distance calculation. The filtering logic is built dynamically based on provided search criteria. ```java public class PropertySearchService { private final EntityManager entityManager; private final LocationService locationService; public PropertySearchService(EntityManager entityManager, LocationService locationService) { this.entityManager = entityManager; this.locationService = locationService; } public List findProperties(PropertySearchCriteria criteria) { Property property = from(Property.class); PropertyFeatures features = innerJoin(property.getFeatures()); // Base conditions where(property.getStatus()).eq(PropertyStatus.AVAILABLE); // Price range if (criteria.getMinPrice() != null) { where(property.getPrice()).gte(criteria.getMinPrice()); } if (criteria.getMaxPrice() != null) { where(property.getPrice()).lte(criteria.getMaxPrice()); } // Property type if (criteria.getPropertyTypes() != null && !criteria.getPropertyTypes().isEmpty()) { where(property.getType()).in(criteria.getPropertyTypes()); } // Minimum bedrooms and bathrooms if (criteria.getMinBedrooms() != null) { where(property.getBedrooms()).gte(criteria.getMinBedrooms()); } if (criteria.getMinBathrooms() != null) { where(property.getBathrooms()).gte(criteria.getMinBathrooms()); } // Specific amenities (using WITH clause on the features join) if (criteria.getRequiredAmenities() != null && !criteria.getRequiredAmenities().isEmpty()) { OnGoingLogicalCondition amenitiesCondition = condition(); for (String amenity : criteria.getRequiredAmenities()) { amenitiesCondition.or(features.getFeatureType()).eq(amenity); } with(amenitiesCondition); } // Location-based filtering if (criteria.getCity() != null && !criteria.getCity().isEmpty()) { where(property.getCity()).eq(criteria.getCity()); } if (criteria.getZipCode() != null && !criteria.getZipCode().isEmpty()) { where(property.getZipCode()).eq(criteria.getZipCode()); } // Execute query Query query = select(property); List results = query.list(entityManager); // Post-processing for distance-based filtering (if coordinates provided) if (criteria.getLatitude() != null && criteria.getLongitude() != null && criteria.getMaxDistanceInMiles() != null) { return results.stream() .filter(p -> locationService.calculateDistanceMiles( criteria.getLatitude(), criteria.getLongitude(), p.getLatitude(), p.getLongitude()) <= criteria.getMaxDistanceInMiles()) .collect(Collectors.toList()); } return results; } } ``` -------------------------------- ### Get Single Result - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Shows how to execute a JPA query and retrieve a single result using TorpedoQuery. This includes filtering with a 'where' clause and executing the query against an EntityManager. ```java Entity entity = from(Entity.class); where(entity.getId()).eq("123"); Query query = select(entity); Entity result = query.get(entityManager); ``` -------------------------------- ### Add a Simple Condition to a Query (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/README.md Explains how to add a `WHERE` clause to filter query results based on a specific condition. This example filters entities by their code. ```java Entity entity = from(Entity.class); where(entity.getCode()).eq("mycode"); org.torpedoquery.jpa.Query conditionalQuery = select(entity); ``` -------------------------------- ### TorpedoQuery: IN with SubQuery (Java) Source: https://github.com/xjodoin/torpedoquery/wiki/IN-query-condition Illustrates using the IN condition with a subquery. This allows filtering based on the results of another query, providing powerful nested querying capabilities. Requires TorpedoQuery's subquery functionality. ```java Entity subQuery = from(Entity.class); Query allCodes = select(subQuery.getCode()); Entity from = from(Entity.class); where(from.getCode()).in(allCodes); Query select = select(from); ``` -------------------------------- ### TorpedoQuery Arithmetic Operation with Subquery Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/subqueries.md Shows how to perform arithmetic operations using the result of a subquery in TorpedoQuery. This example subtracts a constant from a subquery's result to compare with an entity's field. ```java Entity subSelect = from(Entity.class); Entity entity = from(Entity.class); where(entity.getIntegerField()) .eq(select(operation(subSelect.getIntegerField()).subtract(constant(1)))); Query query = select(entity); ``` -------------------------------- ### Java: LIKE Operator Variations for Query Conditions Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/conditions.md Explains the different ways to use the LIKE operator for pattern matching in query conditions in Java, including contains, starts with, and ends with. It also covers the NOT LIKE operator. Parameters for LIKE conditions are generated. ```java Entity entity = from(Entity.class); where(entity.getCode()).like().any("test"); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getCode()).like().startsWith("test"); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getCode()).like().endsWith("test"); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getCode()).notLike().any("test"); Query query = select(entity); ``` -------------------------------- ### Group Conditions with OR in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/conditions.md Demonstrates how to group conditions using parentheses for complex query construction in TorpedoQuery. This example shows grouping an OR condition within an AND condition for more sophisticated filtering logic. The generated HQL uses parentheses for grouping. ```java Entity entity = from(Entity.class); OnGoingLogicalCondition condition = condition(entity.getCode()).eq("test").or(entity.getCode()).eq("test2"); where(entity.getName()).eq("test").and(condition); Query query = select(entity); ``` -------------------------------- ### Access and Modify Query Conditions in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/conditions.md Demonstrates how to retrieve the current condition object from a TorpedoQuery and modify it. This allows for dynamic query building, where conditions can be added or altered based on runtime logic. The example shows accessing the condition and adding a new one. ```java Entity from = from(Entity.class); where(from.getSmallChar()).eq('c'); Query select = select(from.getName()); // Get the current condition Optional condition = select.condition(); if (condition.isPresent()) { condition.get().and(from.getId()).eq("test"); } ``` -------------------------------- ### Dynamic Object Creation (Projections) - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Explains and demonstrates how to create dynamic objects (projections or DTOs) directly from query results using TorpedoQuery's `dyn` and `param` methods. ```java Entity entity = from(Entity.class); Query query = select(dyn(new ProjectionEntity( param(entity.getCode()), param(entity.getIntegerField())))); // Generated HQL: SELECT new org.torpedoquery.jpa.test.bo.ProjectionEntity(entity_0.code, entity_0.integerField) FROM Entity entity_0 ``` -------------------------------- ### Create a Basic Select Query (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/README.md Demonstrates how to construct a simple `SELECT *` equivalent query using Torpedo Query. It initializes a query to select all columns from a given entity. ```java Entity entity = from(Entity.class); org.torpedoquery.jpa.Query selectQuery = select(entity); ``` -------------------------------- ### Clone TorpedoQuery Repository (Bash) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/contributing.md Clones the TorpedoQuery repository from GitHub to your local machine. This is the first step in setting up your development environment for contributing to the project. Ensure you replace 'YOUR_USERNAME' with your actual GitHub username. ```bash git clone https://github.com/YOUR_USERNAME/torpedoquery.git cd torpedoquery ``` -------------------------------- ### Torpedo Class Methods Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/api-reference.md The Torpedo class is the main entry point for creating queries and contains static methods for all main query operations. ```APIDOC ## Torpedo Class Methods ### Description Provides static methods to initiate and build JPQL queries. ### Methods #### `from(Class entityClass)` - **Description**: Creates a proxy for the specified entity class to start building a query. - **Type**: Static Method #### `select(Object... selects)` - **Description**: Creates a query with the given selections. - **Type**: Static Method #### `where(Object object)` - **Description**: Starts building a WHERE clause on the specified field. - **Type**: Static Method #### `condition()` - **Description**: Creates an empty logical condition. - **Type**: Static Method #### `condition(Object object)` - **Description**: Creates a logical condition on the specified field. - **Type**: Static Method #### `innerJoin(Object object)` - **Description**: Creates an inner join with the specified relation. - **Type**: Static Method #### `leftJoin(Object object)` - **Description**: Creates a left join with the specified relation. - **Type**: Static Method #### `rightJoin(Object object)` - **Description**: Creates a right join with the specified relation. - **Type**: Static Method #### `with(OnGoingLogicalCondition condition)` - **Description**: Adds a condition to a join (WITH clause). - **Type**: Static Method #### `with(Object value)` - **Description**: Starts building a WITH condition on a joined relation. - **Type**: Static Method #### `groupBy(Object... groups)` - **Description**: Creates a GROUP BY clause for the specified fields. - **Type**: Static Method #### `orderBy(Object... orders)` - **Description**: Creates an ORDER BY clause for the specified fields. - **Type**: Static Method #### `extend(Object proxy, Class subType)` - **Description**: Extends a proxy to a subtype to access subtype-specific methods. - **Type**: Static Method #### `dyn(Object constructor)` - **Description**: Creates a dynamic instantiation expression (for custom result mapping). - **Type**: Static Method #### `param(Object value)` - **Description**: Used inside `dyn()` to specify constructor parameters. - **Type**: Static Method #### `and(OnGoingLogicalCondition... conditions)` - **Description**: Combines conditions with AND. - **Type**: Static Method #### `or(OnGoingLogicalCondition... conditions)` - **Description**: Combines conditions with OR. - **Type**: Static Method ``` -------------------------------- ### Parameter Handling and Extraction - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Illustrates TorpedoQuery's automatic parameter handling to prevent SQL injection. It shows how to retrieve the generated HQL query string and its associated parameters. ```java Entity entity = from(Entity.class); where(entity.getName()).eq("test"); Query query = select(entity); // Get the query string and parameters String hql = query.getQuery(); Map parameters = query.getParameters(); // Will contain: {"name_1": "test"} ``` -------------------------------- ### Run Tests with Maven (Bash) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/contributing.md Executes all the tests defined within the TorpedoQuery project using Maven. This command ensures that your changes have not introduced any regressions and that all existing functionality remains intact. It's a necessary step before submitting a pull request. ```bash mvn test ``` -------------------------------- ### Build and Execute a Basic JPA Query with TorpedoQuery Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/index.md This Java code snippet demonstrates how to construct a simple JPA query using the TorpedoQuery library. It shows how to import static methods, define the entity and query conditions, and execute the query using an EntityManager. This approach leverages type safety and a fluent API to simplify query creation. ```java import static org.torpedoquery.jpa.Torpedo.* // Create a simple query Entity entity = from(Entity.class); where(entity.getCode()).eq("mycode"); Query query = select(entity); // Execute the query using your EntityManager List results = query.list(entityManager); ``` -------------------------------- ### Filter Collection by Size in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/conditions.md Illustrates how to filter entities based on the size of a collection property using TorpedoQuery. This example checks if the collection size is greater than a specified number. The generated HQL uses the '.size' property. ```java Entity entity = from(Entity.class); where(entity.getSubEntities()).size().gt(2); Query query = select(entity); ``` -------------------------------- ### Import Torpedo Query Core Classes (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/README.md This snippet shows the necessary import statement to begin using Torpedo Query's fluent API for building JPA queries. It allows direct access to static methods like `from` and `select`. ```java import static org.torpedoquery.jpa.Torpedo.* ``` -------------------------------- ### Query Interface Methods Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/api-reference.md The Query interface represents a compiled query ready for execution. ```APIDOC ## Query Interface Methods ### Description Represents a compiled query that can be executed against an EntityManager. ### Methods #### `T get(EntityManager entityManager)` - **Description**: Executes the query and returns a single result. - **Type**: Method #### `List list(EntityManager entityManager)` - **Description**: Executes the query and returns a list of results. - **Type**: Method #### `String getQuery()` - **Description**: Returns the generated HQL/JPQL query string. - **Type**: Method #### `Map getParameters()` - **Description**: Returns the parameter map for the query. - **Type**: Method #### `Optional condition()` - **Description**: Returns the query's condition if it exists. - **Type**: Method ``` -------------------------------- ### Execute a Torpedo Query (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/README.md Shows how to execute a constructed Torpedo Query using an `EntityManager` to retrieve a list of results. This step is crucial for obtaining data from the database. ```java Entity entity = from(Entity.class); org.torpedoquery.jpa.Query selectQuery = select(entity); List entityList = selectQuery.list(entityManager); ``` -------------------------------- ### Left Join with TorpedoQuery Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/joins.md Demonstrates how to perform a left join. This ensures all records from the 'Entity' table are returned, along with matching records from 'SubEntity'. If no match exists in 'SubEntity', its fields will be NULL. ```java Entity entity = from(Entity.class); SubEntity subEntity = leftJoin(entity.getSubEntity()); Query query = select(entity); ``` -------------------------------- ### Set Up Upstream Remote Repository (Bash) Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/contributing.md Adds the original TorpedoQuery repository as a remote named 'upstream'. This allows you to fetch changes from the main project and keep your fork updated. It is essential for managing contributions effectively. ```bash git remote add upstream https://github.com/xjodoin/torpedoquery.git ``` -------------------------------- ### Use and Apply Empty Conditions in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/dynamic-queries.md Demonstrates creating and utilizing empty condition placeholders in TorpedoQuery. These placeholders can be populated later with multiple conditions, and the entire group is applied only if it's not empty, preventing unnecessary WHERE clauses. ```java Entity entity = from(Entity.class); OnGoingLogicalCondition emptyCondition = condition(); Query query = select(entity); // Later in your code, you can add to this condition if (shouldFilterByName()) { emptyCondition.and(entity.getName()).eq("test"); } if (shouldFilterByCode()) { emptyCondition.and(entity.getCode()).like().startsWith("ABC"); } // Finally, apply the condition if it's not empty if (!emptyCondition.isEmpty()) { where(emptyCondition); } ``` -------------------------------- ### Select Multiple Fields - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Demonstrates selecting multiple fields from an entity, resulting in an array of Objects. This is useful for retrieving a subset of data. ```java Entity entity = from(Entity.class); Query query = select(entity.getCode(), entity.getName()); ``` -------------------------------- ### Build Complex Dynamic Conditions in Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/advanced/dynamic-queries.md Illustrates building complex dynamic conditions in TorpedoQuery by grouping multiple OR and AND conditions. This allows for sophisticated filtering logic based on various dynamic inputs. ```java Entity entity = from(Entity.class); // Create a condition group for status filters OnGoingLogicalCondition statusConditions = condition(); if (includeActive()) { statusConditions.or(entity.isActive()).eq(true); } if (includePending()) { statusConditions.or(entity.getStatus()).eq("PENDING"); } // Create a condition group for date filters OnGoingLogicalCondition dateConditions = condition(); if (startDate != null) { dateConditions.and(entity.getDateField()).gte(startDate); } if (endDate != null) { dateConditions.and(entity.getDateField()).lte(endDate); } // Combine the condition groups if (!statusConditions.isEmpty() && !dateConditions.isEmpty()) { where(statusConditions).and(dateConditions); } else if (!statusConditions.isEmpty()) { where(statusConditions); } else if (!dateConditions.isEmpty()) { where(dateConditions); } Query query = select(entity); ``` -------------------------------- ### Handle Date Fields - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Shows how to perform comparisons with Date fields in JPA queries using TorpedoQuery, such as greater than, and how it generates the corresponding HQL. ```java Entity entity = from(Entity.class); where(entity.getDateField()).gt(new Date()); Query query = select(entity); // Generated HQL: SELECT entity_0 FROM Entity entity_0 WHERE entity_0.dateField > :dateField_1 ``` -------------------------------- ### Group Conditions with OR and AND (Java) Source: https://github.com/xjodoin/torpedoquery/blob/master/README.md Illustrates how to construct complex query conditions by grouping them with logical operators like `OR` and `AND`. This enables more sophisticated filtering logic. ```java Entity fromEntity = from(Entity.class); OnGoingLogicalCondition groupedCondition = condition(fromEntity.getCode()).eq("test") .or(fromEntity.getCode()).eq("test2"); where(fromEntity.getName()).eq("test").and(groupedCondition); Query groupedSelect = select(fromEntity); ``` -------------------------------- ### Handle Primitive Types - Java Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/basic-queries.md Demonstrates how TorpedoQuery correctly handles primitive types (like int) in entity fields when building and executing JPA queries, including comparisons. ```java Entity entity = from(Entity.class); where(entity.getPrimitiveInt()).eq(10); Query query = select(entity); // Generated HQL: SELECT entity_0 FROM Entity entity_0 WHERE entity_0.primitiveInt = :primitiveInt_1 ``` -------------------------------- ### Java: Basic Comparison Operators for Query Conditions Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/core-concepts/conditions.md Demonstrates using basic comparison operators like equality, inequality, greater than, less than, and their inclusive variants for building query conditions in Java. These methods operate on entity fields and generate corresponding HQL. ```java Entity entity = from(Entity.class); where(entity.getCode()).eq("test"); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getCode()).neq("test"); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getIntegerField()).gt(2); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getIntegerField()).gte(2); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getIntegerField()).lt(2); Query query = select(entity); Entity entity = from(Entity.class); where(entity.getIntegerField()).lte(2); Query query = select(entity); ``` -------------------------------- ### Import TorpedoFunction Class for JPQL Functions Source: https://github.com/xjodoin/torpedoquery/blob/master/docs/api-reference.md Imports static methods from the TorpedoFunction class, providing access to common JPA/JPQL functions such as COUNT, SUM, MIN, MAX, AVG, and string manipulation functions. This enables their direct use within query constructions. ```java import static org.torpedoquery.jpa.TorpedoFunction.* ```