Entity/User.php
public function persistRoles(LifecycleEventArgs $args)
    {
        $roles = $args->getObject()->getRoles();

        $meta = $args->getObjectManager()->getClassMetadata(get_class($args->getObject()));
        $roleClass = $meta->getAssociationTargetClass('roles');

        $has_default_role = false;
        /** @var EntityManager $em */
        $em = $args->getObjectManager();

        foreach ($roles as $k => $role) {
            try {
                $role_id = $role->getRole();
                if ($role_id === static::ROLE_DEFAULT) {
                    $has_default_role = true;
                }

                if ($em->find($roleClass, $role_id)) {
                    $_ref = $em->getReference($roleClass, $role_id);
                    if ($_ref) {
                        $roles[$k] = $_ref;
                    }
                }
            } catch (ORMException $e) {
                continue;
            }
        }
        if (!$has_default_role) {
            if ($em->find($roleClass, static::ROLE_DEFAULT)) {
                $_ref = $em->getReference($roleClass, static::ROLE_DEFAULT);
                if ($_ref) {
                    $roles[] = $_ref;
                }
            } else {
                $roles[] = new $roleClass(static::ROLE_DEFAULT);
            }
        }

        $args->getObject()->setRoles($roles);
    }
public function persistRoles(LifecycleEventArgs $args)
    {
        $roles = $args->getObject()->getRoles();

        $meta = $args->getObjectManager()->getClassMetadata(get_class($args->getObject()));
        $roleClass = $meta->getAssociationTargetClass('roles');

        $has_default_role = false;
        /** @var EntityManager $em */
        $em = $args->getObjectManager();

        foreach ($roles as $k => $role) {
            try {
                $role_id = $role->getRole();
                if ($role_id === static::ROLE_DEFAULT) {
                    $has_default_role = true;
                }

                if ($em->find($roleClass, $role_id)) {
                    $_ref = $em->getReference($roleClass, $role_id);
                    if ($_ref) {
                        $roles[$k] = $_ref;
                    }
                }
            } catch (ORMException $e) {
                continue;
            }
        }
        if (!$has_default_role) {
            if ($em->find($roleClass, static::ROLE_DEFAULT)) {
                $_ref = $em->getReference($roleClass, static::ROLE_DEFAULT);
                if ($_ref) {
                    $roles[] = $_ref;
                }
            } else {
                $roles[] = new $roleClass(static::ROLE_DEFAULT);
            }
        }

        $args->getObject()->setRoles($roles);
    }
@ORM\PrePersist()

@param LifecycleEventArgs $args