SoFunction
Updated on 2025-03-08

Java's implementation method for querying data based on the field name returned by the front-end

1. Theoretical Overview

  1. Reflection mechanism: The Java reflection mechanism means that in the running state, all properties and methods of any class can be known; for any object, any method and properties of its can be called. This function of dynamically obtaining information and dynamically calling objects is called the reflection mechanism of the Java language.
  2. MyBatis:MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and raw mapping to map interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
  3. Dynamic SQL stitching: In SQL query, SQL statements are dynamically generated based on conditions. MyBatis provides powerful dynamic SQL features including<if><choose><when><otherwise><trim><where><set>Tags such as the ones can easily implement dynamic SQL.

2. Implementation steps

  1. Receive parameters passed by the front end: The front-end passes query conditions through HTTP requests (such as GET or POST), including field names and corresponding values.
  2. Use reflection mechanism to obtain properties of entity class: According to the field name passed by the front end, use the reflection mechanism to obtain the getter method of the corresponding attributes of the entity class so that query conditions can be set later.
  3. Dynamic splicing of SQL statements: Use MyBatis' dynamic SQL function to dynamically splice SQL query statements based on the field names and values ​​passed by the front-end.
  4. Execute the query and return the result: Execute the query through MyBatis and return the result to the frontend.

3. Code examples

The following is a complete example, including front-end requests, back-end controllers, service layer, MyBatis Mapper, and database entity classes.

1. Database Entity Class

package ;
 
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
 
    // 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 Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
         = age;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
         = email;
    }
}

2. MyBatis Mapper interface

package ;
 
import ;
import ;
import ;
import ;
 
import ;
import ;
 
public interface UserMapper {
 
    @SelectProvider(type = , method = "dynamicSelect")
    List&lt;User&gt; dynamicSelect(@Param("params") Map&lt;String, Object&gt; params);
 
    class UserSqlProvider {
        public String dynamicSelect(@Param("params") Map&lt;String, Object&gt; params) {
            return new SQL() {{
                SELECT("*");
                FROM("user");
                if (params != null &amp;&amp; !()) {
                    for (&lt;String, Object&gt; entry : ()) {
                        WHERE(() + " = #{params." + () + "}");
                        // Note: For simplicity, only the equivalent query of a single field is considered.                        // In actual application, it can be extended to support querying multiple fields and multiple conditions                        break; // If there are multiple fields, you need to modify the logic here, such as using AND to connect multiple conditions                    }
                }
            }}.toString();
        }
    }
}

3. Service layer

package ;
 
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
 
@Service
public class UserService {
 
    @Autowired
    private UserMapper userMapper;
 
    public List<User> queryByField(String fieldName, Object value) {
        Map<String, Object> params = new HashMap<>();
        (fieldName, value);
        return (params);
    }
}

4. Backend controller

package ;
 
import ;
import ;
import ;
import .*;
 
import ;
 
@RestController
@RequestMapping("/users")
public class UserController {
 
    @Autowired
    private UserService userService;
 
    @GetMapping("/query")
    public List<User> queryByField(@RequestParam String fieldName, @RequestParam Object value) {
        return (fieldName, value);
    }
}

5. Configuration file (or)

HereAs an example:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
    username: your_username
    password: your_password
    driver-class-name: 
 
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: 

Note: If you configure MyBatis Mapper using annotation, you do not need tomapper-locationsConfiguration.

6. Database table structure

Suppose there is a name in the databaseuserThe table structure is as follows:

CREATE TABLE user (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    age INT,
    email VARCHAR(100)
);

4. Test

Start the Spring Boot application and send HTTP GET requests through a browser or Postman and other tools:

Copy the code

http://localhost:8080/users/query?fieldName=name&amp;value=John

If there is a user named John in the database, all information for that user should be returned.

5. Summary

This article explains in detail how to dynamically query data in the database based on the field names passed by the front-end in the Java back-end. By combining reflection mechanism, MyBatis dynamic SQL splicing and other technologies, we have achieved this function. This sample code can be run directly and has certain reference value and practical significance. In practical applications, the code can be expanded and optimized according to specific needs, such as supporting querying multiple fields, querying multiple conditions, etc.

The above is the detailed content of Java's implementation method for querying data based on the field name returned by the front-end. For more information on querying data by Java field name, please pay attention to my other related articles!