Michel
Michel

Reputation: 681

Hibernate - Custom insert into database

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)

Upvotes: 12

Views: 71888

Answers (2)

Michel
Michel

Reputation: 681

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();

Upvotes: 24

HeavyE
HeavyE

Reputation: 2212

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();

Upvotes: 19

Related Questions