Tuesday, March 16, 2010

Custom Settings and MIXED_DML_OPERATION

Some folks have noticed an issue when using the new Custom Settings feature in Apex. When you have a piece of code that does DML on both a custom setting and a regular object, you get:

"MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)"

What is Mixed DML? Well, certain types of DML simply do not mix well. For instance, if you change a Profile and also an Account (in the same transaction), you might be altering the profile in such a way that it no longer has access to that Account. So, there's a certain set of combinations that will yield a MIXED_DML_OPERATION exception.

In general, the way to get around this is to do your second bit of DML in a @Future method, as that will happen in its own transaction (though it's important to note that, in a test method, @Future method invocations are inlined, so you will still get the MIXED_DML_OPERATION exception).

However, starting in version 18.0, Custom Settings are no longer placed in this special bucket. You can now do DML on Custom Setting objects and other (non-setup) objects in the same transaction.

Just be sure your code is set to version 18.0!

No comments: