How to set up an insert to a grails created file with next sequence number?

守給你的承諾、 提交于 2020-01-06 02:43:29

问题


I'm using a JMS queue to read from and insert data into a postgres table created by grails. The problem is obtaining the next sequence value. I thought I had found the solution with the following statement (by putting "DEFAULT" where the ID should go), but it's no longer working. I must have changed something, because I needed to recreate the table. What's the best way to get around this problem?

ps = c.prepareStatement("INSERT INTO xml_test (id, version, xml_text) VALUES (DEFAULT, 0, ?)");

UPDATE:

In response to the suggested solution, I did the following:

Added this to the the domain:

class XmlTest {
    String xmlText
    static constraints = {
        id generator:'sequence', params:[name:'xmltest_sequence']
    }
}

And changed the insert statement to the following:

ps = c.prepareStatement("INSERT INTO xml_test (id, version, xml_text) 
VALUES (nextval('xmltest_sequence'), 0, ?)");

However, when I run the statement, I get the following error:

[java] 1 org.postgresql.util.PSQLException: ERROR: relation "xmltest_sequence" does not exist

Any thoughts?


回答1:


You can get the value of any sequence in PostgreSQL using nextval function, in your case:

INSERT INTO xml_test (id, version, xml_text) VALUES (nextval('sequence_name_for_this_table'), 0, ?);

And in your grails domain class you can choose the sequence name:

static mapping = {
    id generator:sequence, params:[name:'sequence_name_for_this_table']
}



回答2:


Problem solved.

It turns out that when grails creates a table, it doesn't assign a specific sequence generator to it.

Instead, grails uses a single sequence generator for all tables. This is called "hibernate_sequence".

So, to get around the problem, I included the "nextval" for that in my SQL statement:

ps = c.prepareStatement("INSERT INTO xml_test (id, version, text_field) VALUES (nextval('hibernate_sequence'), 0, ?)");



来源:https://stackoverflow.com/questions/2822623/how-to-set-up-an-insert-to-a-grails-created-file-with-next-sequence-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!