3

I have Subscription entity, which represents one of many-to-many relations between users in Twitter-like following model. It has surrogate ID to ensure the uniqueness of relation, which is represented by Value Object SubscriptionId. SubscriptionId is persisted as a MongoBinData. Here is the XML description:

<document name="Subscription"
          collection="users.subscriptions"
          repository-class="SubscriptionRepository">
    <field name="id" id="true" type="User.Subscription.Id"/>
    <field name="u" fieldName="userId" type="User.Id"/>
    <field name="t" fieldName="subscribedTo" type="User.Id"/>
    <field name="d" fieldName="dateTime" type="PreciseDateTime"/>
</document>

I set id field to Subscription in constructor manually. The problem is that ODM forces upsert operation instead of insert for new entities with IDs. Thus I have no chance to detect duplication (domain events will be raised twice, etc.). This code executes without duplicate exception:

$sub = new Subscription($subscriberId, $subscribedToId);

$dm->persist($sub);
$dm->flush();

$dm->clear();

$dm->persist($sub);
$dm->flush();

I tried to use custom id generator instead of setting id in constructor. But for some reason ODM ignored my type="User.Subscription.Id" and treated ID type as custom_id. My entity had instance of MongoBinData instead of desired SubscriptionId.

I'm looking for a graceful way to achieve the goals:

  1. VO as entity's id
  2. Duplication exception when persisting new entity with existing ID
Vitaly Chirkov
  • 1,692
  • 3
  • 17
  • 33
  • Did you ever find a solution to this? I'm currently stuck. – Oddman Mar 17 '16 at 23:20
  • @Oddman, no, I gave up : ( – Vitaly Chirkov Mar 21 '16 at 14:13
  • @Oddman, now I use string `` combined with unique index by `u` and `t`. – Vitaly Chirkov Mar 21 '16 at 15:32
  • I ended up figuring it out - it's simply how you setup the mapping. Basically, you register a new "type" say its UserId as a value object. You then create a DQL mapping of that type which knows how to fetch the actual value and does the conversion (Ie. if it's a string UUID, then you'd get the string value to be sent). It then also knows how to convert it back. Took me a while to figure out how it worked, but got there eventually. So now I have value objects for each type of id (user id, post id, content id.etc.). – Oddman Mar 23 '16 at 14:51
  • Do you create IDs manually (eg. in constructor) or ODM creates it for you? – Vitaly Chirkov Mar 24 '16 at 12:32
  • I create all my ids manually, as I often want control over them. – Oddman Mar 24 '16 at 22:42

0 Answers0