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