views:

472

answers:

2

I want to write an insert query in Grails. I have tried all possible combinations but cant get the syntax correct. Can anybody please help?

class Person {
    int age
    String name
}

i tried the following:

Person.executeUpdate("insert into Person  values (20,"ABC")")

p.s.:Please do not mention using save()

+2  A: 

It doesn't look possible. See http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-direct and note that it says "Only the INSERT INTO ... SELECT ... form is supported; not the INSERT INTO ... VALUES ... form." So you can insert as a select from one or more other tables, but can't insert directly like you would with save().

Burt Beckwith
Hi Burt thanks for your reply please check my comment on armandino's reply.
WaZ
+3  A: 

Execute a native query:

def sql = new Sql(sessionFactory.currentSession.connection())
sql.execute("insert into person values(?,?)", ["foo", "bar"])

note that person is the actual table name.

armandino
Thanks for you reply,well to be honest my requirement is whenever a record is updated, rather than updating the record a new record should be inserted but with a different timestamp.Is there anything out of the box in grails that I can use to implement this behaviour?Thanks very much.
WaZ
Will a record be updated via save()? e.g. person.save() creates a new person record with a new timestamp instead of updating the existing record?
armandino
How will this requirement fit into database constraints. Just think of a unique constraint on one row of your table. It would not work anymore. As far as I understand you, you want to hold information about changes made to a record. You should have a look at the Envers Plugin for that: http://code.google.com/p/grails-envers-plugin/
codescape