org.hibernate. NonUniqueObjectException: a different object with the same identifier value Part 2
Let's have another look at this and see if we can change our logic up to eliminate the use of EntityLoadByExample. This wasn't working consistently across all similar functions in the application. This method will allow us to eliminate the need for ORMGetSession().merge() methods, or ORMEntityMerge() methods.
We will check to see if an object is returned from EntityLoad using our primary keys.
Here's the code walk through:
First we set all our variables from arguments or ORM defined objects.
2var CompanyCode = getCompany().getCompanyCode();
3var ReferralId = arguments.eventArgs.ReferralId;
4var ReferralSource = arguments.eventArgs.ReferralSource;
5var ReferralEmail = arguments.eventArgs.ReferralEmail;
Next we create or ORM Entity to utilize the methods and attempt to create the object that contains the primary keys for which we are looking.
2var objReferralSource = ReferralSourceArray.EntityLoad(CompanyCode=CompanyCode,ReferralId=ReferralId);
If an object is returned with our primary keys, then we know it already exists in the ORM session. So we test to see if it is an object, and if so, set the other variables.
2 objReferralSource.setEmailAddress(ReferralEmail);
3 objReferralSource.setSource(ReferralSource);
4 }
If an object is not returned, this means that this object does not exist in the ORM session. So we set the variables using the original ORM Entity methods and save. We have to save because it's new and not in the ORM session.
2 ReferralSourceArray.setCompanyCode(CompanyCode);
3 ReferralSourceArray.setEmailAddress(ReferralEmail);
4 ReferralSourceArray.setSource(ReferralSource);
5 ReferralSourceArray.setReferralId(ReferralId);
6 ReferralSourceArray.save(ReferralSourceArray);
7 }
And there we go.....
Here's the whole function for reference:
2 <cfargument name="eventArgs" required="true" />
3 <cfscript>
4var ReferralInfoArray = getCompany().getCompanyInfo().getReferralInfo();
5var CompanyCode = getCompany().getCompanyCode();
6var ReferralId = arguments.eventArgs.ReferralId;
7var ReferralSource = arguments.eventArgs.ReferralSource;
8var ReferralEmail = arguments.eventArgs.ReferralEmail;
9var ReferralSourceArray = application.orm.createEntity("COMPANY_REFERRAL_INFO");
10var objReferralSource = ReferralSourceArray.EntityLoad(CompanyCode=CompanyCode,ReferralId=ReferralId);
11
12 if isObjectt(objReferralSource)){
13 objReferralSource.setEmailAddress(ReferralEmail);
14 objReferralSource.setSource(ReferralSource);
15 }
16 else {
17 ReferralSourceArray.setCompanyCode(CompanyCode);
18 ReferralSourceArray.setEmailAddress(ReferralEmail);
19 ReferralSourceArray.setSource(ReferralSource);
20 ReferralSourceArray.setReferralId(ReferralId);
21 ReferralSourceArray.save(ReferralSourceArray);
22 }
23 </cfscript>
24</cffunction>