Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if an Instance is persisted in the Database with GORM?

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?

like image 413
confile Avatar asked Jul 28 '14 13:07

confile


2 Answers

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.

like image 150
Rafael Werlang Avatar answered Oct 11 '22 12:10

Rafael Werlang


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:

  1. Object is attached to hibernate session or not.
  2. Another object with same id exists or not.

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.

like image 23
CrashOverload Avatar answered Oct 11 '22 13:10

CrashOverload