Implementing business-logic: ConcurrentModificationException
dgdwinte Mar 22, 2008 3:38 PMHi all,
I use a stateless session-bean to implement the business-logic to save entity-beans. The stateless session-bean uses injection of the entitymanager as follows:
@Stateless(mappedName = "PersonDAO") public class PersonDAO extends DAOBasicOperationsAbstractClass<Person> implements PersonDAOInterfaceLocal, PersonDAOInterfaceRemote{ @PersistenceContext(unitName = "texaco", type = PersistenceContextType.TRANSACTION) EntityManager em;
Before saving the "Person"-entitybean, I'd like to do some checks by executing a native read-query in a separate method on the same table (join with other ones) where I'd like to save the Person:
Query query=em.createNativeQuery( querystring ); query.setParameter("TELEPHONENUMBER_1", person.getPhonenumber1()==null?"K":person.getPhonenumber1().getPhoneNumber()); query.setParameter("TELEPHONENUMBER_2", person.getPhonenumber2()==null?"K":person.getPhonenumber2().getPhoneNumber()); query.setParameter("GSMNUMBER_1", person.getGsmnumber1()==null?"K":person.getGsmnumber1().getPhoneNumber()); query.setParameter("GSMNUMBER_2", person.getGsmnumber2()==null?"K":person.getGsmnumber2().getPhoneNumber()); if (update) query.setParameter("ID", person.getId()); Collection<Person> pers_coll=executeMultipleResultQuery(query); if (pers_coll.size()>0) return false; else return true;
If this method returns
true, the new person will not be saved, otherwise he will be saved as follows:
if (!checkPhoneNumberValidity(person, true)) throw new PersonValidationException(); Person person_orig=findById(person.getId()); if (!person_orig.equals(person)){ person_orig.getLatestValidPersonProperty().getValidityinterval().invalidate(); person.getLatestValidPersonProperty().setValidityinterval(new ValidityInterval(new GregorianCalendar(), new GregorianCalendar(2099, 12, 12))); person.getLatestValidPersonProperty().setId(null); person_orig.getPersonproperties().add(person.getLatestValidPersonProperty()); person_orig.setName(person.getName()); person_orig.setFirstname(person.getFirstname()); person_orig.setNationalregisternumber(person.getNationalregisternumber()); person_orig.setIdentitycardnumber(person.getIdentitycardnumber()); person_orig.setBirthdate(person.getBirthdate()); person_orig.setSex(person.getSex()); person_orig.deepValidate(); executeMerge(em, person_orig); }
Please note, I also make some comparisons with the original object as I work with properties. In this scenario, I get a ConcurrentModificationException. Seems logic to me, but how to solve this in a proper way, because the checks must happen within the same transaction.
Any help or advice is very appreciated!
Best regards,
Davy.