前面兩天介紹的query語法基本上跟SQL語法沒有多大的關聯性,屬於比較直觀的寫法,如果要比較複雜的query的話,因為GORM底層是Hibernate,故當然可以用HQL語法(SQL like)的語法來做查詢,今天又是一周的上班第一天,沒有太多時間鑽研太深入的HQL語法,故簡單介紹HQL語法以及用Integration Test來測試HQL語法是否正確,對HQL有興趣的話可以參考
,以及下載Grails官方API來看,裡面也有一些範例
HQL語法基本上還是從Domain Class出發,主要有四種方法:find(), findAll(), executeQuery以及executeUpdate,基本語法如下今天將以findAll為例。
(Domain class name).方法(HQL語法)
以User及Post Domain class為主,兩者是一對多關係,忘記提如果在多的那一方Domain Class中加入belongsTo=[xxx(variable):XXX(Domain Class)],Grails將自動產生新方法addTo*/removeFrom,
(Domain Class Name).addTo*
(Domain Class Name).removeFrom*
以此case為例,則是User.addToPosts(new Post(.....))
使用Integration Test簡單範例code如下:
class PostIntegrationSpec extends IntegrationSpec {
def setup() {
}
def cleanup() {
}
void "Test Adding post function"() {
given:'HQL Syntax Test'
def Jason=new User(userId:'Jason', password:'i74960X',
profile: new Profile(fullName:'JasonGoo', email:'yiren.goo@gmail.com'),
personalPage:'https://www.facebook.com/NeverFigureOut').save(failOnError:true)
def John=new User(userId:'John', password:'JohnWu',
profile: new Profile(fullName:'John Wu', email:'John.wu@gmail.com'),
personalPage:'https://john.blogger.com').save(failOnError:true)
Jason.addToPosts(new Post(content:'Just finish a horrible day...'))
Jason.addToPosts(new Post(content:'What can I do to have more time?'))
Jason.addToPosts(new Post(content:'What a sunny day'))
John.addToPosts(new Post(content:'Today is not my day'))
John.addToPosts(new Post(content:'What a horrible Monday!!!'))
when:'Executing findAll function'
def totalPosts=Post.findAll ("from Post").size()
//findAll回傳是list
def postNumberForJason=Post.findAll("from Post p "+
"where p.user.userId=:name",[name:'Jason']).size()
//使用:namej作為query變數可以避免SQL injection
then: 'Check if how many posts are linked to the user'
5 == totalPosts
3 == postNumberForJason
}
}
Integration Test結果:
| Loading Grails 2.2.3
| Configuring classpath.
| Environment set to test.....
| Packaging Grails application.....
| Packaging Grails application.....
| Compiling 1 source files...
| Running 1 spock test... 1 of 1
| Completed 1 spock test, 0 failed in 544ms
| Tests PASSED - view reports in D:\groovy\JasonMicroBlog\target\test-reports
明天將開始介紹controller的部分...