Naftuli Kay
Naftuli Kay

Reputation: 91630

Named parameterized SQL queries in Java

From poking around in PreparedStatement, it appears that parameterizing SQL statements only allows the developer to specify positional arguments using ? and PreparedStatement.setX(index, value):

PreparedStatement statement = connection.prepareStatement("select * from something where id = ?;");
statement.setString(1, '5'); 

Is there a way to supply named parameters to prepared statements like this:

ParameterizedStatement statement = connection.parameterizeStatement(
    "select * from something where id = $id;");
statement.setString("id", "5");

Does something exist for this in Java?

Upvotes: 2

Views: 120

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

JPA queries can use named parameters, example:

EntityManager em = ...
Query q = em.createQuery("SELECT x FROM Magazine x WHERE x.title = :titleParam and x.price > :priceParam");
q.setParameter("titleParam", "JDJ");
q.setParameter("priceParam", 5.0);
List<Magazine> results = (List<Magazine>) q.getResultList();

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

Not in the base JDK, but this sounds like the MyBatis SQL Builder Class.

For example,

// Anonymous inner class
public String deletePersonSql() {
  return new SQL() {{
    DELETE_FROM("USER");
    WHERE("ID = ${id}");
  }}.toString();
}

// Builder / Fluent style
public String insertPersonSql() {
  String sql = new SQL()
    .INSERT_INTO("USER");
    .VALUES("ID, FIRST_NAME", "${id}, ${firstName}")
    .VALUES("LAST_NAME", "${lastName}")
    .toString(); 
  return sql;
}

Upvotes: 2

Related Questions