Grails: Check if a domain model object was created in code or loaded from the database

StackOverflow https://stackoverflow.com/questions/21562394

  •  07-10-2022
  •  | 
  •  

문제

In Grails (or maybe Hibernate) is it possible to check if a domain model object was created in code (ie: it's a new object that has not yet been saved to the database) or if it was created by being loaded from the database?

도움이 되었습니까?

해결책

You could use method isAttached - http://grails.org/doc/latest/ref/Domain%20Classes/isAttached.html.

Newly created objects are not attached to current session until .save() is called, the objects that were loaded from database are attached to the session.

다른 팁

In grails 1.3.9 isAttached() does not seem to work when used in a Domain class custom validator.

I'm using Date dateCreated grails magic in all my domain objects and that worked against null check in the validator:

    date(blank: false, nullable: false, validator: { val, obj, errors ->
            // Validation only for new objects
            if (obj.dateCreated == null && obj.date <= new Date()) {
                errors.rejectValue('date', 'date.before.now');
            }
        }
    )

In most cases, the domain instance will be assigned an id when it is persisted. So if the id property is null, it hasn't been saved to the database yet. If it came from the database, the instance will have a non-null id.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top