Java Hibernate - 自定义插入数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3707098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate - Custom insert into database
提问by Michel
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:
Crypt 是一个存储在我的数据库中的函数,我想在我的代码中插入它。实际上,当我想在数据库中插入一些东西时,我使用:
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.
但是必须从文件中读取密钥 'cdp',所以这个解决方案对我不起作用。
I want to use a method on my code to execute a SQL query (INSERT query)
我想在我的代码上使用一种方法来执行 SQL 查询(INSERT 查询)
采纳答案by Michel
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();
回答by HeavyE
Like Nathan Feger mentioned, named parameters are much cleaner and safer. In this case, the statement can be executed with the following code:
就像 Nathan Feger 提到的那样,命名参数更干净、更安全。在这种情况下,可以使用以下代码执行语句:
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();