In Java backend development, it is a common requirement to dynamically query the database based on the field names returned by the front-end. This requirement is usually achieved by using reflection and dynamic SQL. Below is a complete code example that shows how to dynamically query data in a database based on the field names returned by the front-end.
1. Example of dynamic querying data in the database based on the field name returned by the front end
1. Preparation
(1) Database settings:
Suppose we have a table called users with the following structure:
CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), age INT );
Insert some test data:
INSERT INTO users (name, email, age) VALUES ('Alice', 'alice@', 30); INSERT INTO users (name, email, age) VALUES ('Bob', 'bob@', 25);
(2) Dependency library:
- use
MySQL
As a database. - use
JDBC
Make a database connection. - use
Spring Boot
Simplify configuration and dependency management (but the example does not involve complex Spring framework features, only focus on core logic).
2. Core code
(1) Database connection configuration
First, insrc/main/resources
Create a directoryFile, configure database connection information:
=jdbc:mysql://localhost:3306/your_database_name =your_database_username =your_database_password -class-name=
(2) Dynamic query tool class
Create a tool classDynamicQueryUtil
, used to generate dynamic SQL based on field names and execute queries:
import .*; import ; import ; import ; import ; import ; import ; @Component public class DynamicQueryUtil { @Value("${}") private String url; @Value("${}") private String username; @Value("${}") private String password; public List<Map<String, Object>> queryByFields(List<String> fields, String tableName) { List<Map<String, Object>> results = new ArrayList<>(); String sql = "SELECT " + (", ", fields) + " FROM " + tableName; try (Connection conn = (url, username, password); Statement stmt = (); ResultSet rs = (sql)) { while (()) { Map<String, Object> row = new HashMap<>(); for (String field : fields) { (field, (field)); } (row); } } catch (SQLException e) { (); } return results; } }
(3) Controller class
Create a controller classUserController
, used to receive front-end requests and call dynamic query tool class:
import ; import ; import ; import .*; @RestController @RequestMapping("/api/users") public class UserController { @Autowired private DynamicQueryUtil dynamicQueryUtil; @GetMapping("/query") public List<Map<String, Object>> queryUsers(@RequestParam List<String> fields) { return (fields, "users"); } }
(4) Startup Class
Create a Spring Boot startup class:
import ; import ; @SpringBootApplication public class DynamicQueryApplication { public static void main(String[] args) { (, args); } }
3. Running example
(1) Start the Spring Boot application.
(2) Use browser or Postman and other tools to send GET requests tohttp://localhost:8080/api/users/query?fields=name,email
。
(3) The response result should be similar to:
[ { "name": "Alice", "email": "alice@" }, { "name": "Bob", "email": "bob@" } ]
4. Things to note
(1)Security: In actual applications, it is necessary to verify the field name and table name passed in by the front-end to prevent SQL injection attacks.
(2)performance: Frequent splicing of SQL strings and creating connections may have an impact on performance, and the use of connection pooling and caching mechanisms should be considered.
(3)Extensibility: More advanced ORM frameworks such as MyBatis or Hibernate can be used to simplify database operations and enhance security and performance.
2. More detailed code examples
Below is a more detailed code example that contains the complete Spring Boot project structure and explains each step in detail. This example will show how to create a simple Spring Boot application that can dynamically query data in the database based on the field names requested by the front-end.
1. Project structure
dynamic-query-example
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── dynamicquery
│ │ │ ├──
│ │ │ ├── controller
│ │ │ │ └──
│ │ │ ├── service
│ │ │ │ └──
│ │ │ ├──
│ │ │ │ └──
│ │ │ ├── util
│ │ │ │ └──
│ │ │ └── model
│ │ │ └──
│ │ ├── resources
│ │ │ ├──
│ │ └── (Optional, used to initialize the database)
│ └── test
│ └── java
│ └── com
│ └── example
│ └── dynamicquery
│ └──
└──
First, make sure ourContains necessary dependencies such as Spring Boot Starter Web and MySQL Connector.
<project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0."> <modelVersion>4.0.0</modelVersion> <groupId></groupId> <artifactId>dynamic-query-example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>dynamic-query-example</name> <description>Demo project for Spring Boot</description> <parent> <groupId></groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId></groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Configure database connection information.
=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC =your_database_username =your_database_password -class-name= -auto=update -sql=true =.MySQL5Dialect
4. Data Model
Define a simpleUser
class, which corresponds to theusers
surface.
package ; import ; import ; import ; import ; @Entity public class User { @Id @GeneratedValue(strategy = ) private Long id; private String name; private String email; private Integer age; // Getters and Setters }
5. Dynamic query tool class
This class will be responsible for generating SQL based on the field name and executing the query. Note that in this example we will not use it directly, but instead use JPA to demonstrate more modern methods. But for the sake of completeness, I still provide the code for this class.
// ... (The code of DynamicQueryUtil class is omitted because it will not be used directly in this example)
Notice: In practical applications, we should use JPAEntityManager
Or Spring Data JPAJpaRepository
to perform dynamic queries instead of using JDBC directly. The followingUserServiceImpl
The class will show how to implement dynamic query using JPA.
6. Service interface
Define a service interface.
package ; import ; import ; public interface UserService { List<Map<String, Object>> findUsersByFields(List<String> fields); }
7. Service implementation category
First, let's assumeUser
The class already exists and containsid
, name
, email
, andage
Properties, as well as corresponding getter and setter methods. We won't show it in full hereUser
Class, because it is usually simple, just contains some basic fields and JPA annotations.
Next, we will improveUser_
class, enabling it to be a simulation of JPA metamodel. In actual projects, we will use the metamodel generator provided by JPA to automatically generate these classes.
The following is completeCode, including a simplified
User
Class definition and perfectUser_
kind:
package ; import ; import ; import ; import ; @Entity public class User { @Id @GeneratedValue(strategy = ) private Long id; private String name; private String email; private Integer age; // Getters and Setters public Long getId() { return id; } public void setId(Long id) { = id; } public String getName() { return name; } public void setName(String name) { = name; } public String getEmail() { return email; } public void setEmail(String email) { = email; } public Integer getAge() { return age; } public void setAge(Integer age) { = age; } } --- package ; import ; import ; import ; import ; import ; import ; import .*; import .*; @Service public class UserServiceImpl implements UserService { @Autowired private EntityManager entityManager; @Override public List<Map<String, Object>> findUsersByFields(List<String> fields) { if (fields == null || ()) { throw new IllegalArgumentException("Fields list cannot be null or empty"); } CriteriaBuilder cb = (); CriteriaQuery<Object[]> cq = (Object[].class); Root<User> user = (); List<Selection<?>> selections = new ArrayList<>(); for (String field : fields) { switch (field) { case "id": (("id")); break; case "name": (("name")); break; case "email": (("email")); break; case "age": (("age")); break; default: throw new IllegalArgumentException("Unknown field: " + field); } } (((new Selection[0]))); TypedQuery<Object[]> query = (cq); List<Object[]> results = (); List<Map<String, Object>> userList = new ArrayList<>(); for (Object[] result : results) { Map<String, Object> userMap = new HashMap<>(); for (int i = 0; i < (); i++) { ((i), result[i]); } (userMap); } return userList; } // Static inner classes are used to simulate JPA's metamodel (Metamodel). Automatically generated metamodels should be used in actual projects. // Note: In actual projects, we do not need to write this class manually, and the JPA provider will automatically generate it for us. // It is included here for demonstration purposes only. private static class User_ { // These fields are simulated and should be automatically generated by JPA tools in practice public static final SingularAttribute<User, Long> id = mockAttribute("id"); public static final SingularAttribute<User, String> name = mockAttribute("name"); public static final SingularAttribute<User, String> email = mockAttribute("email"); public static final SingularAttribute<User, Integer> age = mockAttribute("age"); // Simulation method does not exist in reality private static <T, X> SingularAttribute<T, X> mockAttribute(String name) { return null; // What is actually returned is a SingularAttribute instance generated by the JPA provider } } // Note: The above mockAttribute method is added for compilation and should be removed in the actual code. // In actual projects, we should directly use the metamodel class provided by JPA, rather than this simulated User_ class. // Since this example is to demonstrate dynamic query, we keep the User_ class, but it should be ignored in actual applications.}
Important Note:
(1) In actual projects, we should use the metamodel class automatically generated by JPA providers (such as Hibernate), instead of the aboveUser_
kind. These classes are usually located in the same package as the entity class and are_
Suffix naming (for example,User_
)。
(2) The abovemockAttribute
The method is added for compilation and is removed from the actual code. This method does not exist in the actual project, because it simply simulates the behavior of the JPA metamodel.
(3) Calling(...)
When we use the string attribute name directly (for example,"id"
, "name"
wait). In a real project, we should use static fields in the JPA metamodel class to reference these properties to improve type safety and refactoring capabilities. For example, we should useUser_.id
Instead of"id"
. However, since we simulated the metamodel in this example, we used the string directly.
(4) In actual projects, we may also need to deal with some additional boundary situations, such as case sensitivity of field names, null value processing, etc.
(5) Considering performance and security, dynamic queries should be used with caution and ensure that the incoming field names are verified and authorized.
3. Built-in module to create a basic HTTP server
Here we will use the Python language to write a simple web server as an example, using the built-inModule to create a basic HTTP server. This example will show how to start a server and listen to the request on a specific port, then return a simple HTML response.
1. Code example
# Import the necessary modulesfrom import SimpleHTTPRequestHandler, HTTPServer # Define a custom request processor class, inherited from SimpleHTTPRequestHandlerclass MyRequestHandler(SimpleHTTPRequestHandler): def do_GET(self): # Set the response status code self.send_response(200) # Set response header self.send_header('Content-type', 'text/html') self.end_headers() # Prepare the response body response_body = """ <!DOCTYPE html> <html> <head> <title>Simple Web Server</title> </head> <body> <h1>Hello, World!</h1> <p>This is a simple web server running on Python.</p> </body> </html> """ # Send the response body (response_body.encode('utf-8')) # Define the server's address and portserver_address = ('', 8080) # Create HTTP server object, pass in server address and request processor classhttpd = HTTPServer(server_address, MyRequestHandler) # Print server startup informationprint("Starting httpd server on port 8080...") # Start the server and start listening to requestshttpd.serve_forever()
2. Code description
(1)Import module: First, we importedSimpleHTTPRequestHandler
andHTTPServer
Modules, these two modules are used in the Python standard library to create HTTP servers.
(2)Define the request processor: We created a name calledMyRequestHandler
class inherited fromSimpleHTTPRequestHandler
. In this class, we rewritedo_GET
Method for processing GET requests.
(3)Set up the response:existdo_GET
In the method, we first set the status code of the response (200 means success), then set the response header (specified content type as HTML), and finally prepare the response body (a simple HTML page).
(4)Start the server: We define the address and port of the server (the 8080 port of all interfaces here), and then createHTTPServer
Object and pass in the server address and our custom request processor class. Finally, callserve_forever
Method starts the server and causes it to start listening to requests.
3. Run the code
Save the above code as a Python file (e.g.simple_server.py
), and then run the file on the command line:
python simple_server.py
After the server is started, we can access it in the browserhttp://localhost:8080
, we will see a simple HTML page that says "Hello, World!" and a message that says this is a simple web server.
This example shows how to create a basic web server using modules from the Python standard library and handle HTTP GET requests. As needed, we can further expand this example, add more request handling methods, handle POST requests, or get parameters from the request, etc.
This is the article about how Java query data based on the field name returned by the front-end. For more information about Java field name query data, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!