Search code examples
grailsgrails-orm

determine if domain object is persistent


How can I determine if a domain class instance is persistent, i.e. was loaded from a database? I'm looking for a property/method that would return false for this object

def book = new Book(name: 'foo')

But would return true for this object

def book = Book.findByName('foo')

Is checking for a truthy id property reliable, e.g.

boolean isPersistent = book.id

Solution

  • Use the isAttached method or its attached property form:

    def book = new Book(name: 'foo')
    assert !book.attached
    
    book.save(flush: true)
    
    Book.withSession { it.clear() }
    book = Book.findByName('foo')
    assert book.attached
    

    If you don't use assigned ids, checking that the instance has a non-null id will work but isn't always going to be correct since you can always assign a long value to the id property of a non-persistent instance (it will be updated when saved).

    Note that using isAttached will fail for persistent instances that are detached from a Hibernate Session - it's only true if both persistent (i.e. it was instantiated from database data) and currently associated with a session.