Java 如何编写HQL插入查询?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32653692/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:54:44  来源:igfitidea点击:

How to write HQL Insert query?

javamysqlhibernate

提问by Ganesa Vijayakumar

I am struggling to write a HQL query for inserting a new record in a table. I have seen some of insert query as below but I don't want insert data from another table as below code.

我正在努力编写用于在表中插入新记录的 HQL 查询。我已经看到了一些如下的插入查询,但我不想从另一个表中插入数据,如下所示。

String hql = "INSERT INTO Employee(firstName, lastName, salary)"  + 
             "SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

For example I have a table "User" with three fields like name, age, number and I have entity for this user table. what will be the insert query for this?

例如,我有一个表“用户”,其中包含三个字段,如姓名、年龄、号码,并且我有这个用户表的实体。这个插入查询是什么?

采纳答案by StanislavL

In HQL, only the INSERT INTO … SELECT … is supported; there is no INSERT INTO … VALUES. HQL only support insert from another table.

在 HQL 中,仅支持 INSERT INTO … SELECT …;没有 INSERT INTO ... VALUES。HQL 只支持从另一个表插入。

So query INSERT from SELECT is possible like this

所以从 SELECT 查询 INSERT 是可能的

Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
                "select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

Got from here secion 4

这里得到第4 节

If you have values and Entity just call

如果你有价值观和实体只是打电话

MyEntity e=new MyEntity();
e.setXXXX(the XXX values);
save(e);

回答by Elon Than

HQLdoesn't support such INSERTs so you have to do this by creating and persisting new entity.

HQL不支持此类INSERTs,因此您必须通过创建和持久化新实体来做到这一点。

You can read about it here.

你可以在这里阅读它。

Only the INSERT INTO ... SELECT ... form is supported. You cannot specify explicit values to insert.

仅支持 INSERT INTO ... SELECT ... 形式。您不能指定要插入的显式值。

回答by Carlos López Marí

You can do:

你可以做:

Foo foo = new Foo(any, columns, you, want);
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();

session.save(foo); //Here you have the magic

session.getTransaction().commit();
session.close();

Just make sure you add all the values set as "not null", or you′ll get a nullException.

只要确保你添加了所有设置为“not null”的值,否则你会得到一个 nullException。