Vinod Vinod - 1 month ago 8
Groovy Question

How to execute hibernate queries in groovy classes?

I am new to Groovy before I was working on java. I am using .groovy classes in AribaWeb. I need to connect to my DB and save the values in the DB.

I have configured the database details in build.xml as follows,

<property value="com.mysql.jdbc.Driver" name="hibernate.connection.driver_class"/>
<property value="jdbc:mysql://localhost:3307/test" name="hibernate.connection.url"/>
<property value="root" name="hibernate.connection.username"/>
<property value="axxonet" name="hibernate.connection.password"/>
<property value="org.hibernate.dialect.MySQLInnoDBDialect" name="hibernate.dialect"/>
<property value="update" name="hibernate.hbm2ddl.auto" />


Now I have a groovy class I need to save the values in DB, How can we create the session and connect to DB and insert the values in database in .groovy class. I am using ant for configuration.

Answer

you have 2 options basically:

  1. use GORM standalone, as nicely described here. You'll be able to run a query like:

def p = Person.findByFirstName(firstName)

or any other GORM or hibernate query

  1. use groovy.sql.Sql class (see docs. it doesn't have hibernate on board, but is really powerful if you need to get the things done as simple and as fast as possible:

def db = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbc.JDBCDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)

sql.eachRow( "select * from person" ){ row -> println "$row.id -> $row.userame , $row.firstName" }

Comments