12

I write this post to know if someone knows how to do this:

I want to do this insert:

INSERT INTO TABLA (CAMPO1, CAMPO2) VALUES (?, crypt(?,'cdp'))

Crypt is a function stored in my database and the insert I would want to do it in my code. Actually when I want to insert something in the database I use:

getHibernateTemplate().persist(obj);

But I want to do a "custom" insert, because I need to use that function.

I am using hibernate + annotations:

@org.hibernate.annotations.SQLInsert (sql = "INSERT INTO TABLA (CAMPO1, CAMPO2) VALUES (?, crypt(?,'cdp'))")

But the key 'cdp' must be readed from a file, so this solution doesn't work for me.

I want to use a method on my code to execute a SQL query (INSERT query)

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Michel
  • 681
  • 2
  • 7
  • 17
  • Is this doable using raw SQL (in other words, let's put Hibernate aside)? If yes, I don't understand why the `@SQLInsert` doesn't work for you. If not, I'm afraid Hibernate won't help. Can you clarify? – Pascal Thivent Sep 14 '10 at 08:12
  • Doesn't work for me because I need to get a String with the cryption key, so I don't know how to introduce it on the @SQLInsert – Michel Sep 14 '10 at 08:24

2 Answers2

24

Here's a solution:

Query query = getSession().createSQLQuery("INSERT INTO TABLA (CAMPO1, CAMPO2) VALUES (:valor1, encripta(:valor2, :key))");
query.setParameter("valor1", valor1);
query.setParameter("valor2", valor2);
query.setParameter("key", key);
query.executeUpdate();
Matt Passell
  • 4,549
  • 3
  • 24
  • 39
Michel
  • 681
  • 2
  • 7
  • 17
19

Like Nathan Feger mentioned, named parameters are much cleaner and safer. In this case, the statement can be executed with the following code:

Query query = getSession().createSQLQuery("INSERT INTO TABLA (CAMPO1, CAMPO2) VALUES (:valor1, encripta(:valor2, :key))");
query.setParameter("valor1", valor1);
query.setParameter("valor2", valor2);
query.setParameter("key", key);
query.executeUpdate();
HeavyE
  • 2,132
  • 1
  • 23
  • 31