You can using spring
JDBC or JPA. It depends on what you are using already. When using spring JDBC, you will be creating JDBC queries. When using JPA, you will be using JPA queries
However, remember that dynamic queries are the major source of security holes that arise due to SQL injection. You can prevent SQL injection by using prepared statements/paramaterized named queries. If you are creating queries dynamically,
you should make sure the queries are not created from user input, and if they are they are sanitized.