When I save an instance as:
test.save()
the save could fail. I could do
if (!test.save(flush:true) {
// save failed
}
Consider that case that I got an instance from another function and could not do this check because I will not save the instance again.
Is there a way to check if an instance is still persisted in the data base or has the unsaved state?
I know this is an old question but for future reference I think the appropriate answer would be this:
Given the OP's original question
Is there a way to check if an instance is still persisted in the data base or has the unsaved state?
Yes, there is. Call the exists() method of the domain class of your instance.
Suppose we have a Test domain class and a test object instance:
def bPersists = ( test.id != null && Test.exists(test.id) ); // Check test.id for null because a id of zero is a valid index, also the id might not be an integer.
Notice the check if test.id equals to null instead of just checking if it evaluates to true. That is because an id equal to zero would evaluate to false but it is actually a valid id number. Also the id could be a string or other data type.
Original answer:
Ultimately you want to save the object, so if its already saved
test.save(flush:true)
will automatically save/update the object. Also, hibernate ensures that there is only one persisted instance of each object, if there are more than one such instances you'll get error while fetching the other one.
Edited Answer:
Since you don't want to save the object you'll have to check two things:
Following code should do it:
def exists = test.id?Test.get(test.id):false
def isPersisted = false
if(test.isAttached() || exists){
isPersisted = true
}
I hope it solves your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With