简体   繁体   English

使用EntityManager执行SQL命令

[英]Executing an SQL command with EntityManager

Is it possible to run an SQL script that doesn't return a resultSet or is not an INSERT or UPDATE type of script? 是否可以运行不返回resultSet或不是INSERT或UPDATE类型的脚本的SQL脚本?

I'm trying the following: 我正在尝试以下方法:

Query q = entityManager.createNativeQuery("DECLARE @max int;\n" +
        "SELECT @max = MAX(customer_number)+1\n" +
        "FROM organisation\n" +
        "\n" +
        "exec('ALTER SEQUENCE organisation_customer_number_seq RESTART WITH ' + @max)");

...but of course that just creates the query, how to execute it? ...但是当然只创建查询,如何执行查询? I can only find getters for different types of resultSets and executeUpdate method for Query. 我只能找到不同类型的resultSet的getter和Query的executeUpdate方法。 How to just run that query I created above to restart a sequence? 如何只运行上面创建的查询以重新启动序列?

Some of the methods you see in Query actually execute the query, eg Query.getResultList : 您在Query看到的一些方法实际上会执行查询,例如Query.getResultList

getResultList() getResultList()

Execute a SELECT query and return the query results as an untyped List. 执行SELECT查询,并以无类型的List返回查询结果。

List<Object[]> results = q.getResultList();

UPDATE : in your case the query ends up being an ALTER so as you figured it out, the relevant method will be executeUpdate() which returns no list or value, but the number of affected rows. UPDATE:在您的情况下,查询最终变为ALTER因此您就知道了,相关的方法将是executeUpdate() ,它不返回列表或值,但返回受影响的行数。

int executeUpdate() int executeUpdate()

Execute an update or delete statement. 执行更新或删除语句。

int altered =  q.executeUpdate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM