Programming & Development / April 19, 2025

Using LIKE %?% in Prepared Statements with JDBC and MyBatis

SQL LIKE clause JDBC prepared statement MyBatis LIKE wildcard search parameterized query SQL injection safe Java database MyBatis annotations

When performing partial string matches in SQL, the LIKE operator is a powerful tool. In Java, using it safely and effectively with prepared statements helps prevent SQL injection while still supporting dynamic queries. This article shows how to use LIKE '%?%' style queries in both JDBC and MyBatis.

1. Using LIKE in JDBC with PreparedStatement

✅ Code Example

java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JdbcLikeExample {

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "your_username";
        String password = "your_password";

        String searchKeyword = "example"; // The value you want to search for

        String query = "SELECT * FROM your_table WHERE column_name LIKE ?";

        try (Connection connection = DriverManager.getConnection(url, username, password);
             PreparedStatement preparedStatement = connection.prepareStatement(query)) {

            // Wildcards are added around the keyword
            preparedStatement.setString(1, "%" + searchKeyword + "%");

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                System.out.println(resultSet.getString("column_name"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

🧠 Explanation

  • You pass the wildcard % as part of the parameter.
  • This allows the database to match any value that contains the keyword, not just exact matches.
  • Using PreparedStatement ensures the query remains secure against SQL injection.

2. Using LIKE in MyBatis

You can do the same with MyBatis using either XML-based or annotation-based configuration.

a) XML Mapper Example

xml

<select id="selectByKeyword" parameterType="String" resultType="YourEntity">
    SELECT * FROM your_table
    WHERE column_name LIKE CONCAT('%', #{keyword}, '%')
</select>

b) Annotation-Based Mapper Example

java

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;

public interface YourMapper {

    @Select("SELECT * FROM your_table WHERE column_name LIKE CONCAT('%', #{keyword}, '%')")
    List<YourEntity> selectByKeyword(@Param("keyword") String keyword);
}

🧠 Explanation

  • #{keyword} is the placeholder for the parameter.
  • CONCAT('%', #{keyword}, '%') adds the wildcards dynamically in SQL.
  • This matches records where the column contains the keyword as a substring.

3. Summary

ApproachHow Wildcard is AppliedSafe from SQL InjectionJDBCWildcard % is added in Java ("%keyword%")✅ YesMyBatis XMLUse CONCAT('%', #{keyword}, '%') in query✅ YesMyBatis Anno.Use CONCAT in @Select query✅ Yes

Final Notes

  • Always use parameterized queries or MyBatis bindings—never concatenate user input directly into SQL strings.
  • For other wildcards:
  • % matches any sequence of characters.
  • _ matches a single character.

Example Output

Assuming you have records like:

pgsql

| column_name  |
|--------------|
| testexample  |
| anexample    |
| sampletext   |

A search for "example" will match testexample and anexample, but not sampletext.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex