我想通了。
我採取了不同的路線(更多谷歌搜索後)。我將dateCreated
添加到由Grails管理的模型中,以便它自動更新。所以我所需要做的就是獲得最新日期的記錄(每年我們將爲下一個財年增加一個新記錄)。在調用結束時注意[0]
,這會使返回的數組數組變平,並允許我處理單個對象。
我的模型現在看起來像這樣(MYAPPConfig.groovy):
class MYAPPConfig {
String fiscalYear
Integer requestCount
Date dateCreated
static constraints = {
fiscalYear (size: 4..4, nullable: false)
requestCount(max: 999, nullable: false)
}
}
我創建了以下服務(ManageRequestsService.groovy)
import grails.transaction.Transactional
@Transactional
class ManageRequestService {
def getNextTrackingId() {
def latestConfig = MYAPPConfig.listOrderByDateCreated(max:1, order: "desc")[0]
def latestFiscal = latestConfig.fiscalYear
Integer sequence = latestConfig.requestCount
sequence++
latestConfig.requestCount = sequence
latestConfig.save(flush:true)
return latestFiscal + sprintf('%03d', sequence)
}
}
而且在我的控制器中(MyTestController.groovy)我有:
class MyTestController {
def manageRequestsService
def test() {
def trackingId = manageRequestsService.getNextTrackingId()
render "Next id is: ${trackingId}"
}
}
給予以下輸出(http://localhost:8080/MYAPP/myTest/test
):
下一個ID:2015001
刷新頁面!
下一個ID:2015002
再次刷新!
下一個ID:2015003
這是意志的作品好就多節點配置? – wwarlock 2014-08-28 06:22:24
我想,你可以在某個時間得到兩個相同的「序列」數字。 – wwarlock 2014-08-28 06:25:09
我希望@Transactional註釋可以照顧到這一點。沒有進一步閱讀。任何人有更多的細節背後是什麼? – 2014-08-28 17:44:34