### Complete Export SearchBean Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/anno.md A comprehensive example of an export SearchBean, demonstrating relaxed rate limits and field mappings with export annotations. ```java @SearchBean( tables = "order o, user u", where = "o.buyer_id = u.id", autoMapTo = "o", maxSize = 2000, // relax per-batch query limit maxOffset = Long.MAX_VALUE // relax pagination-depth limit ) public class OrderExportVO { @Export(name = "Order No.", idx = 1) private String orderNo; @Export(name = "Buyer Name", idx = 2) @DbField("u.name") private String buyerName; @Export(name = "Order Time", idx = 3, format = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; @Export(name = "Amount (USD)", idx = 4, format = "#,##0.00") private BigDecimal amount; @Export(name = "Status", idx = 5, expr = "status == 1 ? 'Paid' : status == 2 ? 'Shipped' : 'Other'") private Integer status; @Export(name = "Phone", idx = 6, onlyIf = "showPhone") private String buyerPhone; // getters / setters omitted } ``` -------------------------------- ### Git Commit Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/README.md Example of a Git commit message format for submitting changes. Use 'feat' for new features and specify the function. ```bash git commit -am 'feat(function): add xxxxx' ``` -------------------------------- ### User Entity Class Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/field.md An example of a Java entity class used to demonstrate field parameter derivation. ```java public class User { private String name; // Omit other.. } ``` -------------------------------- ### Example of Index Array Parameter Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/advance/filter.md Demonstrates how to pass array parameters using index notation, supported when IndexArrayParamFilter is enabled. ```http GET /user/list ? age[0]=20 & age[1]=30 & age-op=bt ``` -------------------------------- ### Complete Export VO Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/ex/anno.md A comprehensive example of an export Value Object (VO) using @SearchBean to configure data retrieval and @Export annotations to define the structure and content of the exported data. ```java @SearchBean( tables = "order o, user u", where = "o.buyer_id = u.id", autoMapTo = "o", maxSize = 2000, // 放开单批查询条数限制 maxOffset = Long.MAX_VALUE // 放开分页深度限制 ) public class OrderExportVO { @Export(name = "订单编号", idx = 1) private String orderNo; @Export(name = "买家姓名", idx = 2) @DbField("u.name") private String buyerName; @Export(name = "下单时间", idx = 3, format = "yyyy-MM-dd HH:mm:ss") private LocalDateTime createTime; @Export(name = "订单金额(元)", idx = 4, format = "#,##0.00") private BigDecimal amount; @Export(name = "订单状态", idx = 5, expr = "status == 1 ? '已支付' : status == 2 ? '已发货' : '其他'") private Integer status; @Export(name = "手机号", idx = 6, onlyIf = "showPhone") private String buyerPhone; // 省略 Getter / Setter } ``` -------------------------------- ### Run Grails Demo Application Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/info/bean-searcher.md Navigate to the Grails demo directory and execute the 'grails run-app' command to start the application. This demo requires JDK 8+. ```bash # This demo is based on JDK 8+ cd bean-searcher/bean-searcher-demos/bs-demo-grails grails run-app ``` -------------------------------- ### Configuring Field Parameter Separator Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/field.md Example of configuring the separator for field parameter names in application.properties. ```properties bean-searcher.params.separator = _ ``` -------------------------------- ### Custom Expresser Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/fwriter.md Demonstrates how to implement a custom Expresser bean using MVEL for expression evaluation. This example shows how to pass the current field value as `_` to the MVEL context. ```APIDOC ## Custom Expresser ### Description This section provides an example of creating a custom `Expresser` bean. This implementation utilizes the MVEL library to evaluate expressions. It sets up a context where `_` refers to the current field's value and includes all fields of the object. You can extend this to include other variables or logic as needed. ### Method Not Applicable (Bean Definition) ### Endpoint Not Applicable (Bean Definition) ### Parameters Not Applicable (Bean Definition) ### Request Example Not Applicable (Bean Definition) ### Response Not Applicable (Bean Definition) ### Code Example (Java) ```java @Bean public Expresser myExpresser() { return (expr, obj, value) -> { Map context = new HashMap<>(); context.put("_", value); // _ refers to the current field value // add all object fields to context... return MVEL.eval(expr, context); }; } ``` ``` -------------------------------- ### Java Group By and Aggregate Function Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Demonstrates grouping by course ID and calculating the total score for each course using an aggregate function. ```java @SearchBean( tables = "student_course sc", groupBy = "sc.course_id" // Group by course ID ) public class CourseScore { @DbField("sc.course_id") private long courseId; @DbField("sum(sc.score)") // The total score of this course (Aggregate function: sum) private long totalScore; // ... } ``` -------------------------------- ### Slow SQL Log Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/slowsql.md This is an example of a slow SQL log entry, indicating the execution time, SQL statement, parameters, and entity class. ```log 14:55:02.151 WARN - bean-searcher [600ms] slow-sql: [select count(*) s_count from employee e where (e.type = ?)] params: [1] on [com.example.sbean.Employee] ``` -------------------------------- ### Page Pagination Usage Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/page.md Demonstrates how to perform page pagination using the MapUtils.builder. Page 0 with 15 items per page is shown as the recommended way. ```java Map params = MapUtils.builder() .page(0, 15) // Page 0, 15 items per page (recommended way) .put("page", 0) // Equivalent way .put("size", 15) // Equivalent way .build(); SearchResult result = searcher.search(User.class, params); ``` -------------------------------- ### Implementing a Custom LabelLoader Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/label/info.md Create a custom `LabelLoader` implementation to define how labels are fetched. This example loads user names based on IDs. ```java import cn.zhxu.bean.searcher.label.LabelLoader; import cn.zhxu.bean.searcher.label.Label; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import java.util.stream.Collectors; @Component public class UserLabelLoader implements LabelLoader { @Autowired private UserService userService; @Override public boolean supports(String key) { return "buyerName".equals(key); } @Override public List> load(String key, List ids) { return userService.findAllById(ids).stream() .map(u -> new Label<>(u.getId(), u.getName())) .collect(Collectors.toList()); } } ``` -------------------------------- ### Custom FileWriter Implementation (Excel) Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/fwriter.md Example of implementing the FileWriter interface to support custom formats like Excel. ```APIDOC ## Custom FileWriter (Excel Example) ### Description This section demonstrates how to create a custom `FileWriter` implementation, such as `ExcelFileWriter`, to support formats beyond CSV. ### Interface Implementation An `ExcelFileWriter` implements the `FileWriter` interface to write data into an Excel workbook. ```java public class ExcelFileWriter implements FileWriter { private final OutputStream output; private Workbook workbook; private Sheet sheet; private int rowIndex = 0; public ExcelFileWriter(OutputStream output) { this.output = output; } @Override public void writeStart(List fields) throws IOException { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet("Data"); Row header = sheet.createRow(rowIndex++); for (int i = 0; i < fields.size(); i++) { header.createCell(i).setCellValue(fields.get(i).getExName()); } } @Override public void writeAndFlush(List fields, List dataList) throws IOException { for (Object data : dataList) { Row row = sheet.createRow(rowIndex++); for (int i = 0; i < fields.size(); i++) { row.createCell(i).setCellValue(fields.get(i).text(data)); } } } @Override public void writeStop(List fields) throws IOException { workbook.write(output); workbook.close(); } @Override public void onTooManyRequests() throws IOException { throw new ExportException.TooManyRequests("Too many export requests."); } } ``` ``` -------------------------------- ### Offset Pagination Usage Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/page.md Illustrates offset pagination using the MapUtils.builder. An offset of 0 items and a query of 15 items is the recommended approach. ```java Map params = MapUtils.builder() .limit(0, 15) // Offset 0 items, query 15 items (recommended way) .put("offset", 0) // Equivalent way .put("size", 15) // Equivalent way .build(); SearchResult result = searcher.search(User.class, params); ``` -------------------------------- ### Query 3 Employees Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-grails/README.md Example JSON response when querying for 3 employees. ```json { "dataList":[ { "age":22, "department":"Finance", "entryDate":"2019-06-23T04:01:01Z", "id":1, "name":"Jack" }, { "age":21, "department":"Technical", "entryDate":"2019-06-24T04:01:01Z", "id":2, "name":"Tom" }, { "age":23, "department":"Market", "entryDate":"2019-06-21T04:01:01Z", "id":3, "name":"Alice" } ], "summaries":[], "totalCount":20 } ``` -------------------------------- ### Example of Array Value Parameter Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/advance/filter.md Demonstrates how to pass multiple values for the same parameter using array syntax, which is supported when ArrayValueParamFilter is enabled. ```http GET /user/list ? age=20 & age=30 & age-op=bt ``` -------------------------------- ### Custom Formatter Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/fwriter.md Provides an example of how to create a custom Formatter bean to modify the output of formatted values. This example appends ' USD' to BigDecimal values. ```APIDOC ## Custom Formatter ### Description This endpoint demonstrates how to define a custom `Formatter` bean. The provided example customizes the formatting for `BigDecimal` values by appending " USD" to the formatted output. For other types, it falls back to the default formatter. ### Method Not Applicable (Bean Definition) ### Endpoint Not Applicable (Bean Definition) ### Parameters Not Applicable (Bean Definition) ### Request Example Not Applicable (Bean Definition) ### Response Not Applicable (Bean Definition) ### Code Example (Java) ```java @Bean public Formatter myFormatter() { return (format, value) -> { if (value instanceof BigDecimal) { return new DecimalFormat(format).format(value) + " USD"; } return Formatter.DEFAULT.format(format, value); }; } ``` ``` -------------------------------- ### Custom Delay Policy Example (Java) Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/control.md Implement a custom DelayPolicy to linearly scale the delay based on the ratio of active exporting threads to the maximum allowed. ```java @Bean public DelayPolicy myDelayPolicy() { // Linearly scale delay with concurrency return (delayMills, exportingThreads, maxExportingThreads) -> { float ratio = (float) exportingThreads / maxExportingThreads; return (int) (delayMills * (1 + ratio)); }; } ``` -------------------------------- ### Query Employee by Name Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-grails/README.md Example JSON response when querying for an employee named Jack. ```json { "dataList":[ { "age":22, "department":"Finance", "entryDate":"2019-06-23T04:01:01Z", "id":1, "name":"Jack" } ], "summaries":[], "totalCount":1 } ``` -------------------------------- ### Logical Expression Examples Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/param/group.md Demonstrates various valid logical expressions using group names, OR ('|'), AND ('&'), and parentheses for nesting. Spaces are allowed around operators and parentheses. ```string A A|B A&B (A&(B|C)|D)&F ``` -------------------------------- ### Java Where Subquery Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Illustrates filtering students based on their average exam score using a where subquery. ```java @SearchBean( tables = "student s", // Only query students whose average exam score is passing (Where subquery) where = "(select avg(sc.score) from student_course sc where sc.student_id = s.id) >= 60" ) public class GoodStudent { @DbField("s.name") private String name; // ... } ``` -------------------------------- ### Registering BuyerLabelLoader as a Spring Bean Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/label/load.md Example of registering a custom LabelLoader (BuyerLabelLoader) as a Spring Bean. The framework automatically scans and registers such beans. ```java @Bean public LabelLoader buyerLabelLoader() { return new BuyerLabelLoader(); } ``` -------------------------------- ### User Entity with Annotations and Inheritance Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/bean/inherit.md An example of a User entity inheriting from BaseEntity, with annotations for table mapping and field mapping. ```java @SearchBean(tables="user u, role r", where="u.role_id = r.id", autoMapTo="u") public class User extends BaseEntity { // 父类与子类中的未被注解的字段都映射到 user 表 private long id; private String username; private int roleId; @DbField("r.name") private String roleName; } ``` -------------------------------- ### Configure Dialect in Other Java Projects Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/dialect.md Configure the SQL dialect and related components programmatically in Java for projects not using Spring. This example sets up the Oracle dialect and associated resolvers. ```java Dialect dialect = new MyDialect(); // Since v3.3, you need to configure the operator pool FieldOpPool fieldOpPool = new FieldOpPool(); fieldOpPool.setDialect(dialect); // Configure to use the Oracle dialect DefaultParamResolver paramResolver = new DefaultParamResolver(); paramResolver.setFieldOpPool(fieldOpPool); DefaultSqlResolver sqlResolver = new DefaultSqlResolver(); sqlResolver.setDialect(dialect); // Configure to use the Oracle dialect MapSearcher mapSearcher = SearcherBuilder.mapSearcher() // Other property configurations are omitted. The BeanSearcher retriever is configured in the same way .paramResolver(paramResolver) .sqlResolver(sqlResolver) .build(); ``` -------------------------------- ### Run Solon Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/info/bean-searcher.md Execute the Solon demo project. Requires JDK 8+. ```bash # This demo is based on JDK 8+ cd bean-searcher/bean-searcher-demos/bs-demo-solon ``` -------------------------------- ### Java Distinct Deduplication Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Shows how to use the distinct attribute to get unique courses from exam records. ```java // Courses in which exams are taken @SearchBean( tables = "student_course sc, course c", where = "sc.course_id = c.id", distinct = true // Deduplication ) public class ExamCourse { @DbField("c.id") private String courseId; @DbField("c.name") private String courseName; // ... } ``` -------------------------------- ### Java Default Sorting Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Defines default sorting rules (age descending, height ascending) for a User entity, used when no sorting parameters are provided. ```java @SearchBean(orderBy = "age desc, height asc") public class User { // ... } ``` -------------------------------- ### Field Filtering (Starts With) Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/start/use.md Filters data based on string fields starting with a specified prefix. ```APIDOC ## GET /user/index?name=Jack&name-op=sw ### Description Returns a list of users where the 'name' field starts with 'Jack'. 'sw' stands for StartWith. ### Method GET ### Endpoint /user/index ### Query Parameters - **name** (string) - Optional - The prefix to match at the beginning of the 'name' field. - **name-op** (string) - Optional - The operator for the 'name' field. 'sw' stands for StartWith. Example: `name-op=sw`. ``` -------------------------------- ### Clone and Run Grails Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-grails/README.md Steps to clone the repository and run the Grails application. ```bash > git clone https://github.com/troyzhxu/bean-searcher.git > cd bean-searcher/bean-searcher-demos/grails-demo > grails > run-app ``` -------------------------------- ### Configure Dynamic Datasource Bean Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/datasource.md Register the `DynamicDatasource` as a Spring Bean and set its target data sources. This example uses a `HashMap` to map tenant IDs to specific `DataSource` instances. ```java // Register the DynamicDatasource as a Bean. @Bean public DataSource dynamicDatasource() { DynamicDatasource dynamicDatasource = new DynamicDatasource(); dynamicDatasource.setTargetDataSources(getAllDataSources()); return dynamicDatasource; } private Map getAllDataSources() { Map dataSources = new HashMap<>(); dataSources.put("Tenant 1 ID", new DataSource1()); dataSources.put("Tenant 2 ID", new DataSource2()); // Put all data sources into the dataSources map. return dataSources; } ``` -------------------------------- ### Field Filtering: Starts With (sw) Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/start/use.md Filters results where the specified string field starts with the provided prefix. ```APIDOC ## GET /user/index ### Description Filters results where the 'name' field starts with 'Jack'. ### Method GET ### Endpoint /user/index ### Query Parameters - **name** (string) - Required - The prefix to match. - **name-op** (string) - Required - The operator to use. Set to 'sw' (starts with). ### Request Example ``` GET /user/index?name=Jack&name-op=sw ``` ### Response #### Success Response (200) - The structure is the same as the default response, but only returns data where the name starts with 'Jack'. ``` -------------------------------- ### Enum Field Conversion Example Entity Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/convertor.md Example of an entity class with an Enum field for use with EnumFieldConvertor. ```java public class User { private Gender gender; // Omit other... } ``` -------------------------------- ### Run Bean Searcher Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-sb2/README.md Steps to clone the repository, navigate to the demo directory, and run the Spring Boot application using Maven. ```bash > git clone https://github.com/troyzhxu/bean-searcher.git > cd bean-searcher/bean-searcher-demos/spring-boot-demo > mvn spring-boot:run ``` -------------------------------- ### Clone and Run Bean Searcher Solon Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-solon/README.md Instructions to clone the repository and run the Solon demo project. Assumes IDEA IDE for opening and running. ```bash > git clone https://github.com/troyzhxu/bean-searcher.git > cd bean-searcher/bean-searcher-demos/bs-demo-solon > IDEA 打开运行 ``` -------------------------------- ### Field Filtering: Starts With (sw) Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/start/use.md Filter results where the 'name' field starts with the substring 'Jack'. 'sw' stands for StartWith. ```HTTP GET /user/index? name=Jack & name-op=sw ``` -------------------------------- ### Run Spring Boot 3 Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/info/bean-searcher.md Execute the Spring Boot 3 demo project. Requires JDK 17+. ```bash # This demo is based on JDK 17+ cd bean-searcher/bean-searcher-demos/bs-demo-sb3 ./gradlew bootRun ``` -------------------------------- ### Run Spring Boot 2 Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/info/bean-searcher.md Execute the Spring Boot 2 demo project. Requires JDK 8+. ```bash # This demo is based on JDK 8+ cd bean-searcher/bean-searcher-demos/bs-demo-sb2 mvn spring-boot:run ``` -------------------------------- ### Clone and Run Bean Searcher Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-sb3/README.md Steps to clone the repository and run the Spring Boot 3.x demo application. ```bash > git clone https://github.com/troyzhxu/bean-searcher.git > cd bean-searcher/bean-searcher-demos/bs-demo-sb3 > ./gradlew bootRun ``` -------------------------------- ### Basic BuyerLabelLoader Implementation Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/label/load.md A sample implementation of LabelLoader that loads buyer names using a UserService. It supports the 'buyerName' key and requires a UserService bean. ```java @Component public class BuyerLabelLoader implements LabelLoader { @Autowired private UserService userService; @Override public boolean supports(String key) { return "buyerName".equals(key); } @Override public List> load(String key, List ids) { List users = userService.findAllById(ids); return users.stream() .map(u -> new Label<>(u.getId(), u.getName())) .collect(Collectors.toList()); } } ``` -------------------------------- ### Clone and Run Bean Searcher Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-demos/bs-demo-sb4/README.md Steps to clone the repository and run the Spring Boot 4 demo using Gradle. ```bash > git clone https://github.com/troyzhxu/bean-searcher.git > cd bean-searcher/bean-searcher-demos/bs-demo-sb4 > ./gradlew bootRun ``` -------------------------------- ### Specify Field Inheritance Mode Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/inherit.md Example of specifying only field inheritance for UserDetail using InheritType.FIELD. ```java @SearchBean( // Specify to only inherit fields inheritType = InheritType.FIELD ) public class UserDetail extends User { private int age; private int status; private int roleType; } ``` -------------------------------- ### Run Spring Boot 4 Demo Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/info/bean-searcher.md Execute the Spring Boot 4 demo project. Requires JDK 21+. ```bash # This demo is based on JDK 21+ cd bean-searcher/bean-searcher-demos/bs-demo-sb4 ./gradlew bootRun ``` -------------------------------- ### Java Select Subquery Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Demonstrates using a select subquery to calculate the total score for a student. ```java @SearchBean(tables = "student s") public class Student { @DbField("s.name") private String name; // The total score of this student (Select subquery) @DbField("select sum(sc.score) from student_course sc where sc.student_id = s.id") private int totalScore; // ... } ``` -------------------------------- ### Constructing Search Parameters with MapUtils.builder Source: https://github.com/troyzhxu/bean-searcher/blob/dev/README.zh-CN.md Demonstrates how to programmatically build complex search parameters using `MapUtils.builder`. This approach allows for fluent construction of select clauses, filters, sorting, and pagination. Ensure `Operator` enum is imported. ```java import com.ejlchina.searcher.SearchBean; import com.ejlchina.searcher.util.MapUtils; import com.ejlchina.searcher.Operator; import java.util.List; import java.util.Map; // Assuming User class and beanSearcher are defined elsewhere Map params = MapUtils.builder() .selectExclude(User::getJoinDate) // 排除 joinDate 字段 .field(User::getStatus, 1) // 过滤:status = 1 .field(User::getName, "Jack").ic() // 过滤:name = 'Jack' (case ignored) .field(User::getAge, 20, 30).op(Operator.Between) // 过滤:age between 20 and 30 .orderBy(User::getAge, "asc") // 排序:年龄,从小到大 .page(0, 15) // 分页:第 0 页, 每页 15 条 .build(); List users = beanSearcher.searchList(User.class, params); ``` -------------------------------- ### JSON Response with Selected Fields Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/start/use.md Example of a JSON response when `onlySelect` is used to retrieve only 'id' and 'name' fields. ```JSON { "dataList": [ // 用户列表,默认返回第 1 页(只包含 id 和 name 字段) { "id": 1, "name": "Jack" },,, ], "totalCount": 100 // 用户总数 } ``` -------------------------------- ### Bean Searcher Boot Starter v4.0.2 Updates Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/info/versions.md New configurations and improvements for the Bean Searcher Spring Boot Starter. ```APIDOC ## Bean Searcher Boot Starter v4.0.2 Updates ### Compatibility * Supports Spring Boot 3 (also supports SpringBoot 1.4 ~ 2.x). ### New Configuration Properties * `bean-searcher.sql.default-mapping.around-char`: Configures identifier wrapper characters (e.g., MySQL's ` `). * `bean-searcher.field-convertor.use-json`: Enables automatic addition of `JsonFieldConvertor` (default: `true`). * `bean-searcher.field-convertor.json-fail-on-error`: Configures whether to throw exceptions on JSON parsing errors (default: `true`). * `bean-searcher.field-convertor.use-list`: Enables automatic addition of `ListFieldConvertor` (default: `true`). * `bean-searcher.field-convertor.list-item-separator`: Configures the separator for splitting string fields into `List`. ### Configuration Improvement * `bean-searcher.field-convertor.date-formats`: Supports using `-` instead of `:` for date formats in YAML configuration. ``` -------------------------------- ### Configuring Field Parameter Operator Suffix Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/field.md Example of configuring the suffix for field operator parameter names in application.yml. ```yaml bean-searcher: params: operator-key: "op" ``` -------------------------------- ### User Entity for Table Inheritance Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/inherit.md A User entity with @SearchBean annotation, serving as a parent for table inheritance. ```java @SearchBean(tables="user u, role r", where="u.role_id = r.id", autoMapTo="u") public class User { private long id; private String username; private int roleId; @DbField("r.name") private String roleName; } ``` -------------------------------- ### Configure Default Table Mapping in Non-Boot Spring Projects Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/aignore.md Set up default database mapping configurations for table prefix, underscore case, and uppercase conversion in non-Boot Spring projects using XML bean definitions. ```xml ``` -------------------------------- ### Backend Parameter Construction for Equal Operator Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/field.md Demonstrates how to construct backend parameters using `MapUtils.builder` to query users by name. The `eq` operator is used, which is the default and can often be omitted. Various equivalent syntaxes for specifying the field and operator are shown. ```java Map params = MapUtils.builder() .field("name", "Jack") // (1) The value of the field `name` is Jack .field(User::getName, "Jack") // Equivalent to (1) .op("eq") // (2) Specify the operator of the `name` field as `eq` (the default is `eq`, so it can also be omitted) .op("Equal") // Equivalent to (2) .op(FieldOps.Equal) // Equivalent to (2) .op(Equal.class) // Equivalent to (2) .build(); User jack = searcher.searchFirst(User.class, params); // Execute the query ``` -------------------------------- ### Custom ExportFieldResolver Bean Configuration Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/exporter.md Configures a custom ExportFieldResolver as a Spring Bean. This example uses DefaultExportFieldResolver with a custom formatter. ```java @Bean public ExportFieldResolver exportFieldResolver(Expresser expresser) { return new DefaultExportFieldResolver(expresser, new MyFormatter()); } ``` -------------------------------- ### Java Field Alias Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Illustrates manually specifying an alias 'date' for a formatted date field, which can then be used in groupBy. ```java @SearchBean( tables = "user u", groupBy = "date" // Group by alias ) public class UseData { @DbField("count(u.id)") private long count; // The number of user registrations per day // Format the registration date to the day and specify the alias: date @DbField(value = "DATE_FORMAT(u.date_created, '%Y-%m-%d')", alias="date") private String dateCreated; // ... } ``` -------------------------------- ### Define Base Entity Class Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/inherit.md Example of a base entity class with common attributes like id, version, and timestamps. ```java public class BaseEntity { private long id; private long version; private Date createAt; private Date updateAt; } ``` -------------------------------- ### Custom BuyerLabelLoader Implementation Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/label/load.md A basic implementation of LabelLoader to translate buyer IDs to names. It supports a specific key 'buyerName' and uses a UserService to fetch user data in batches. ```java @Component public class BuyerLabelLoader implements LabelLoader { @Autowired private UserService userService; @Override public boolean supports(String key) { // 仅处理 key 为 "buyerName" 的标签字段(即字段名未指定 key 时,默认 key = 字段名) return "buyerName".equals(key); } @Override public List> load(String key, List ids) { // 批量查询用户名 List users = userService.findAllById(ids); return users.stream() .map(u -> new Label<>(u.getId(), u.getName())) .collect(Collectors.toList()); } } ``` -------------------------------- ### Bean Searcher Expression Merging Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/group.md Demonstrates how Bean Searcher merges front-end and back-end expressions using an AND relationship when configured to do so. ```text Front-end: `A|B` Back-end: `groupExpr(A|C)` Final: `(A|B)&(A|C)` ``` -------------------------------- ### Configure Dialect in Non-Boot Spring Projects (XML) Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/dialect.md Configure the SQL dialect and related components using XML in non-boot Spring projects. This example defines the Oracle dialect and sets up the operator pool, parameter resolver, and SQL resolver. ```xml ``` -------------------------------- ### SQL Log Configuration Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/start/use.md Instructions on how to enable and view SQL execution logs for Bean Searcher. ```APIDOC ## SQL Log Configuration ### Description To view the SQL execution logs generated by Bean Searcher, you need to adjust the logging level for the `cn.zhxu.bs.implement.DefaultSqlExecutor` class in your logging configuration file. ### Enabling SQL Logs Set the logging level to `DEBUG` to see both slow SQL logs and regular SQL logs. Setting it to `INFO` or `WARN` will only show slow SQL logs. ### Configuration Examples **SpringBoot `application.yml`:** ```yaml logging: level: cn.zhxu.bs: DEBUG ``` **SpringBoot `application.properties`:** ```properties logging.level.cn.zhxu.bs=DEBUG ``` **Other Frameworks:** Refer to the provided Logback configuration examples for SpringBoot and Grails projects. ### Supported Logging Frameworks Bean Searcher uses `slf4j-api` as its logging facade, making it compatible with various logging frameworks like Logback, Log4j, etc. ``` -------------------------------- ### Custom FileWriter.Factory for Local Files Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/ex/fwriter.md Example of overriding the default FileWriter.Factory in a Spring Boot project to save exported files to a local directory. ```java @Bean public FileWriter.Factory fileWriterFactory() { // 示例:将导出文件保存到本地磁盘 return filename -> { File file = new File("/data/export/" + filename + ".csv"); return new CsvFileWriter(new FileOutputStream(file)); }; } ``` -------------------------------- ### Configure Default and User Data Sources in Spring Boot Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/datasource.md Configure data source properties in application.properties for Spring Boot. This example sets up a default data source and a specific data source for user-related entities. ```properties # Default data source spring.datasource.url = jdbc:h2:~/test spring.datasource.driverClassName = org.h2.Driver spring.datasource.username = sa spring.datasource.password = 123456 # User data source spring.datasource.user.url = jdbc:h2:~/user spring.datasource.user.driverClassName = org.h2.Driver spring.datasource.user.username = sa spring.datasource.user.password = 123456 ``` -------------------------------- ### Basic @SearchBean with Multi-Table Mapping Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/bean/annos.md Demonstrates mapping a Java class to multiple database tables with a join condition and specifying a default table for auto-mapping fields. ```java @SearchBean( tables = "users u, roles r", where = "u.role_id = r.id", autoMapTo = "u" ) public class UserWithRole { private Long id; // 自动映射到 u.id private String name; // 自动映射到 u.name @DbField("r.name") private String roleName; // 显式映射到 r.name } ``` -------------------------------- ### Define Grouped Parameters in Properties Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/param/group.md Use group names as prefixes for field parameters to group them. For example, 'A.name' and 'A.gender' belong to group 'A'. ```properties # A 组:姓名 Jack ,不区分大小写,并且是 男性 A.name = Jack A.name-ic = true A.gender = Male # B 组:姓名 Alice,并且是 女性 B.name = Alice B.gender = Female # C 组:年龄 大于等于 20 岁 C.age = 20 C.age-op = ge ``` -------------------------------- ### Configuring Field Parameter Ignore Case Suffix Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/param/field.md Example of configuring the suffix for field parameter names indicating ignore case in application.yml. ```yaml bean-searcher: params: ignore-case-key: "ic" ``` -------------------------------- ### Export Orders - Simplest Form Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/exporter.md Use this method for the simplest export scenario, relying on all default configurations for file naming and output. ```java @GetMapping("/order/export") public void exportOrders() throws IOException { beanExporter.export("orders", OrderExportVO.class); } ``` -------------------------------- ### Java Group By with Having Condition Example Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Shows how to apply a 'having' condition to filter grouped results, specifically for courses with an average score above 50. ```java @SearchBean( tables = "student_course sc", groupBy = "sc.course_id", // Group by course ID having = "avg(sc.score) > 50" // having condition (since v3.8.0) ) ``` -------------------------------- ### Other Environments Configuration Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/interceptor.md For other environments, SQL interceptors can be added to the `SearcherBuilder`. ```APIDOC ## Other Environments Configuration ### Description For other environments, SQL interceptors can be added to the `SearcherBuilder`. ### Configuration Example ```java MapSearcher mapSearcher = SearcherBuilder.mapSearcher() // Other attribute configurations are omitted. The BeanSearcher retriever is configured in the same way .addInterceptor(new MyFirstSqlInterceptor()) .addInterceptor(new MySecondSqlInterceptor()) .build(); ``` ``` -------------------------------- ### EnumLabelLoader with Key Prefix Filtering Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/label/load.md Demonstrates how to configure EnumLabelLoader to only process keys that start with a specific prefix, such as 'enum.'. This helps in avoiding key collisions. ```java // 只处理 key 以 "enum." 开头的标签字段 new EnumLabelLoader("enum.") ``` -------------------------------- ### Customizing FileWriter Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/ex/fwriter.md Instructions on how to implement a custom FileWriter for different file formats like Excel. ```APIDOC ### Custom FileWriter If you need to support other formats (like Excel), you can implement the `FileWriter` interface: ```java public class ExcelFileWriter implements FileWriter { private final OutputStream output; private Workbook workbook; private Sheet sheet; private int rowIndex = 0; public ExcelFileWriter(OutputStream output) { this.output = output; } @Override public void writeStart(List fields) throws IOException { workbook = new SXSSFWorkbook(); sheet = workbook.createSheet("Data"); // Write header Row header = sheet.createRow(rowIndex++); for (int i = 0; i < fields.size(); i++) { header.createCell(i).setCellValue(fields.get(i).getExName()); } } @Override public void writeAndFlush(List fields, List dataList) throws IOException { for (Object data : dataList) { Row row = sheet.createRow(rowIndex++); for (int i = 0; i < fields.size(); i++) { row.createCell(i).setCellValue(fields.get(i).text(data)); } } } @Override public void writeStop(List fields) throws IOException { workbook.write(output); workbook.close(); } @Override public void onTooManyRequests() throws IOException { throw new ExportException.TooManyRequests("Too many export requests, please try again later"); } } ``` ``` -------------------------------- ### Export with Data Transformation Source: https://context7.com/troyzhxu/bean-searcher/llms.txt Exports employee data after applying a transformation to each batch. This example filters the data to include only active employees before writing to the CSV. ```java beanExporter.export("employees", EmployeeExport.class, params, list -> { // Transform each batch before writing return list.stream() .filter(e -> e.getStatus() == 1) // Filter active only .toList(); }); ``` -------------------------------- ### EnumLabelLoader Registration Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/label/load.md Example of registering EnumLabelLoader as a Spring Bean. It demonstrates how to associate enum classes with functions that extract the label text from enum instances. ```java @Bean public EnumLabelLoader enumLabelLoader() { return new EnumLabelLoader() .with(OrderStatus.class, OrderStatus::getLabel) // 注册订单状态枚举的标签函数 .with(GenderType.class, g -> g.name().toLowerCase()); // 注册性别枚举的标签函数 } ``` -------------------------------- ### Basic Join Query with Bean Searcher Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/zoo/label/info.md Demonstrates a standard join query using `@SearchBean` to associate order and user tables, mapping user ID to buyer name. ```java import cn.zhxu.bean.searcher.SearchBean; import cn.zhxu.bean.searcher.DbField; @SearchBean( tables = "order o, user u", where = "o.buyer_id = u.id", // 关联关系 autoMapTo = "o" ) public class OrderVO { private long id; // 订单ID private long buyerId; // 买家ID @DbField("u.name") private String buyerName; // 买家名 u.name // 省略 Getter Setter } ``` -------------------------------- ### Configure Date Formats Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/zh/guide/info/versions.md Optimize the `date-formats` configuration by using '-' instead of ':' to avoid issues with YAML key parsing. ```properties bean-searcher.field-convertor.date-formats= yyyy-MM-dd HH:mm:ss ``` -------------------------------- ### Convert JSON String to POJO with @DbField Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/advance/convertor.md Example showing how to use @DbField(type = DbType.JSON) to convert a JSON string in the database to a POJO field. ```java public class User { // Database value: {id: 1, name: "Administrator"} @DbField(type = DbType.JSON) private Role role; // Omit other fields... } ``` -------------------------------- ### Custom FileNamer Bean Configuration Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/zoo/ex/exporter.md Provides a custom FileNamer implementation as a Spring Bean. This example appends the current date in BASIC_ISO_DATE format to the filename. ```java @Bean public FileNamer fileNamer() { return name -> name + "_" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE); } ``` -------------------------------- ### Configure Bean Searcher with Java Source: https://github.com/troyzhxu/bean-searcher/blob/dev/bean-searcher-doc/docs/en/guide/bean/otherform.md Instantiate and configure DbMapping and MapSearcher programmatically using Java. This approach is suitable for projects not using Spring XML configuration. ```java DefaultDbMapping dbMapping = new DefaultDbMapping(); dbMapping.setDefaultSortType(SortType.ONLY_ENTITY); // Configure the default inheritance type here MapSearcher mapSearcher = SearcherBuilder.mapSearcher() // Other configurations are omitted. .metaResolver(new DefaultMetaResolver(dbMapping)) // The BeanSearcher retriever is configured in the same way. .build(); ```