gpt4 book ai didi

用于保存域对象的 Grails 可重用服务

转载 作者:行者123 更新时间:2023-12-01 10:57:40 27 4
gpt4 key购买 nike

我有一个包含多个域类的 Grails 项目,我想通过在其中只包含一个 save() 来使持久性服务尽可能可重用。为了尝试实现这一点,我在我的项目中做了以下工作。

//PersistenceService.groovy

@Transactional
class PersistenceService {
def create(Object object) {
object.save flush: true
object
}

//BaseRestfulController

class BaseRestfulController extends RestfulController {

def persistenceService

def save(Object object) {
persistenceService.create(object)
}

//图书 Controller

class BookController extends BaseRestfulController {

private static final log = LogFactory.getLog(this)

static responseFormats = ['json', 'xml']

BookController() {
super(Book)
}

@Transactional
def save(Book book) {
log.debug("creating book")

super.save(book)

}

所以基本上我有一堆域,例如 Author 等,每个域都有自己的 Controller ,类似于 bookController。那么有没有办法像我在上面尝试的那样重用服务以实现持久性?

谢谢

最佳答案

我正在做类似的事情,但主要是因为我的所有实体实际上并未从数据库中删除,而是“标记”为已删除。对于多个应用程序,您需要这种方法,因为它对于防止任何类型的数据丢失至关重要。

由于大多数数据库不支持这种情况,因此在删除父域实例时不能依赖外键来删除依赖域实例。所以我有一个名为 GenericDomainService 的基本服务类,它具有保存、删除(标记)、取消删除(取消标记)的方法。

此服务提供可应用于任何域的基本实现。

class GenericDomainService {

def save( instance ) {
if( !instance || instance.hasErrors() || !instance.save( flush: true ) ) {
instance.errors.allErrors.each {
if( it instanceof org.springframework.validation.FieldError ) {
log.error "${it.objectName}.${it.field}: ${it.code} (${it.rejectedValue})"
}
else {
log.error it
}
}
return null
}
else {
return instance
}
}

def delete( instance, date = new Date() ) {
instance.dateDisabled = date
instance.save( validate: false, flush: true )
return null
}

def undelete( instance ) {
instance.dateDisabled = null
instance.save( validate: false, flush: true )
return null
}

}

然后,在我的 Controller 模板中,我总是声明两个服务:通用服务和具体服务(可能不存在):

def ${domainClass.propertyName}Service
def genericDomainService

这会将名为 Book 的域翻译成:

def bookService
def genericDomainService

在 Controller 方法中,我使用如下服务:

def service = bookService ?: genericDomainService
service.save( instance )

最后,给定域的服务将从该域继承,为这些操作提供(如果需要)自定义逻辑:

class BookService extends GenericDomainService {

def delete( instance, date = new Date() ) {
BookReview.executeUpdate( "update BookReview b set b.dateDisabled = :date where b.book.id = :bookId and b.dateDisabled is null", [ date: date, bookId: instance.id ] )
super.delete( instance, date )
}

def undelete( instance ) {
BookReview.executeUpdate( "update BookReview b set b.dateDisabled = null where b.dateDisabled = :date and b.book.id = :bookId", [ date: instance.dateDisabled, bookId: instance.id ] )
super.undelete( instance )
}

}

希望对您有所帮助。

关于用于保存域对象的 Grails 可重用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26042533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com