0

Is there a way to have named parameters in Java MySQL query?

Like this:

SELECT * FROM table WHERE col1 = :val1 AND col2 = :val2

instead of this:

SELECT * FROM table WHERE col1 = ? AND col2 = ?

UPDATE: Im' using java.sql.*, however would be interested in alternatives capable of this.

Naftali
  • 144,921
  • 39
  • 244
  • 303
Caballero
  • 11,546
  • 22
  • 103
  • 163

3 Answers3

0

Maybe Hibernate is good choice for you. It provided the query style as your description, and it's so powerful and convenient to do persistence work that you'll feel cool. e.g

Query query = sesion.createQuery("from Student s where s.age = :age");
query.setProperties(student);


see the doc:http://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#setParameter(java.lang.String, java.lang.Object)

Hunter Zhao
  • 4,589
  • 2
  • 25
  • 39
0

The excellent JDBI library lets you do this and much more.

David Phillips
  • 10,723
  • 6
  • 41
  • 54
0

Yes, there are alternatives. By example, with javax.persistence.* you can achieve that quite easily.

http://docs.oracle.com/javaee/6/tutorial/doc/bnbrg.html

An entity manager will allow you to create dynamic (parametrized) queries with the methods EntityManager.createQuery, and EntityManager.createNamedQuery.