简体   繁体   English

如何在Groovy类中执行休眠查询?

[英]How to execute hibernate queries in groovy classes?

I am new to Groovy before I was working on java. 在从事Java工作之前,我是Groovy的新手。 I am using .groovy classes in AribaWeb. 我在AribaWeb中使用.groovy类。 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, 我已经在build.xml中配置数据库详细信息,如下所示:

    <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. 现在,我有一个groovy类,我需要将值保存在DB中,我们如何创建会话并连接到DB并在.groovy类中将值插入数据库中。 I am using ant for configuration. 我正在使用ant进行配置。

you have 2 options basically: 您基本上有2个选择:

  1. use GORM standalone , as nicely described here . 使用GORM standalone ,如描述很好这里 You'll be able to run a query like: 您将能够运行如下查询:

def p = Person.findByFirstName(firstName) def p = Person.findByFirstName(firstName)

or any other GORM or hibernate query 或任何其他GORM或休眠查询

  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: 使用groovy.sql.Sql类(请参阅docs 。它没有groovy.sql.Sql休眠功能,但是如果您需要尽可能简单快速地完成任务,它确实非常强大:

def db = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbc.JDBCDriver'] def db = [url:'jdbc:hsqldb:mem:testDB',用户:'sa',密码:'',驱动程序:'org.hsqldb.jdbc.JDBCDriver']
def sql = Sql.newInstance(db.url, db.user, db.password, db.driver) 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" } sql.eachRow(“ select * from person”){行-> println“ $ row.id-> $ row.userame,$ row.firstName”}

First, import where the Session variable is. 首先,导入Session变量所在的位置。 Then run the query. 然后运行查询。 For example: 例如:

import java.util.List

import org.hibernate.Query
import org.hibernate.Session

Session session = HibernateUtils.getSession()
def query = <YOUR INSERT QUERY STATEMENT>
def queryResults = session.createQuery(query)
def result = queryResults.executeUpdate()

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

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