0

Using Java 11 and JDBC.
Having PostgreSQL table "employee":

enter image description here

I need to have an ability to select data, but I don't know in advance, what WHERE conditions would be used.

It could be:

SELECT * FROM employee WHERE job_name='PRESIDENT';
SELECT * FROM employee WHERE job_name='PRESIDENT' OR salary>6000;
SELECT * FROM employee WHERE salary<5000 AND manager_id=68319;

Writing all possible SQL in the code, would take a lot of time.

Probably, there is some library, that already has implementation for it.

5
  • Maybe do something like in this question? Commented Jun 10, 2020 at 8:48
  • 1
    you can consider to use jpa. It help to map tables to java entities and help to reduce native query like this Commented Jun 10, 2020 at 8:54
  • @SoT doesn't JPA require Spring to run? That may be a lot of overhead when solely wanting to simplify some SQL queries Commented Jun 10, 2020 at 9:03
  • @Artur are you writing a web app or desktop app? If desktop, refer this link stackoverflow.com/questions/10582586/… Commented Jun 10, 2020 at 9:27
  • When do you know what whereclause you need? You can build your SQL-Statements as string with dynamic where clauses. But use Parameters for your variables. You don't need Spring for JPA. Commented Jun 10, 2020 at 9:27

1 Answer 1

1

Try sqlBuilder [http://sqlobject.org/SQLBuilder.html]. it has support to build dynamic where clauses based on condition. something like below

  var query = SQL
  .SELECT("*")
  .FROM("employee")
  .WHERE()
  ._If(job_name=="PRESIDENT", "job_name = {0}", job_name)

  .ORDER_BY("job_name"); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.