当前位置: 首页 > 知识库问答 >
问题:

原则\ ORM \ Mapping \实体上列“username”的重复定义出现异常

裴哲
2023-03-14

我使用的是FOSUserBundle,但我想将旧数据库的角色字段列名重命名为user_role,

通过引用

https://github.com/FriendsOfSymfony/FOSUserBundle/issues/338

https://github . com/friendsofsofymfony/fouser bundle/blob/master/Resources/doc/doctrine . MD # replacing-the-mapping-of-the-bundle

我试图通过再次映射所有字段,用我的AcmeDemoBundle:User实体覆盖现有的FOS\UserBundle\Model\User。

这是我的班级,

请注意,我是直接从“FOS\UserBundle\Model\User”扩展实体

namespace Acme\SecurityBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Acme\CommonBundle\Util\Url as Url;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="Acme\SecurityBundle\Entity\UserRepository") 
 */
Class User extends BaseUser
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="username", type="string", length=255)     
     */
    protected $username;

    /**
     * @var string
     * @ORM\Column(name="username_canonical", type="string", length=255, unique=true)     
     */
    protected $usernameCanonical;

    /**
     * @var string
     * @ORM\Column(name="email", type="string", length=255)       
     */
    protected $email;

    /**
     * @var string
     * @ORM\Column(name="email_canonical", type="string", length=255, unique=true)       
     */
    protected $emailCanonical;

    /**
     * @var boolean
     * @ORM\Column(name="enabled", type="boolean")         
     */
    protected $enabled;

    /**
     * The salt to use for hashing
     *
     * @var string
     * @ORM\Column(name="salt", type="string")     
     */
    protected $salt;

    /**
     * Encrypted password. Must be persisted.
     *
     * @var string
     * @ORM\Column(name="password", type="string")     
     */
    protected $password;

    /**
     * Plain password. Used for model validation. Must not be persisted.
     *
     * @var string     
     */
    protected $plainPassword;

    /**
     * @var \DateTime
     * @ORM\Column(name="last_login", type="datetime", nullable=true)       
     */
    protected $lastLogin;

    /**
     * Random string sent to the user email address in order to verify it
     *
     * @var string
     * @ORM\Column(name="confirmation_token", type="string", nullable=true)     
     */
    protected $confirmationToken;

    /**
     * @var \DateTime
     * @ORM\Column(name="password_requested_at", type="datetime", nullable=true)         
     */
    protected $passwordRequestedAt;

    /**
     * @var Collection
     */
    protected $groups;

    /**
     * @var boolean
     * @ORM\Column(name="locked", type="boolean")       
     */
    protected $locked;

    /**
     * @var boolean
     * @ORM\Column(name="expired", type="boolean")         
     */
    protected $expired;

    /**
     * @var \DateTime
     * @ORM\Column(name="expires_at", type="datetime", nullable=true)      
     */
    protected $expiresAt;

    /**
     * @var array
     * @ORM\Column(name="fos_roles", type="array", nullable=true)
     */
    protected $roles;

    /**
     * @var boolean
     * @ORM\Column(name="credentials_expired", type="boolean")     
     */
    protected $credentialsExpired;

    /**
     * @var \DateTime
     * @ORM\Column(name="credentials_expire_at", type="datetime", nullable=true)     
     */
    protected $credentialsExpireAt;


    public function __construct()
    {
        parent::__construct();
        $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
        $this->enabled = false;
        $this->locked = false;
        $this->expired = false;
        $this->roles = array();
        $this->credentialsExpired = false;
        //$this->setEmailHash();
    }
    public function addRole($role)
    {
        $role = strtoupper($role);
        if ($role === static::ROLE_DEFAULT) {
            return $this;
        }

        if (!in_array($role, $this->roles, true)) {
            $this->roles[] = $role;
        }

        return $this;
    }

    /**
     * Serializes the user.
     *
     * The serialized data have to contain the fields used by the equals method and the username.
     *
     * @return string
     */
    public function serialize()
    {
        return serialize(array(
            $this->password,
            $this->salt,
            $this->usernameCanonical,
            $this->username,
            $this->expired,
            $this->locked,
            $this->credentialsExpired,
            $this->enabled,
            $this->id,
        ));
    }

    /**
     * Unserializes the user.
     *
     * @param string $serialized
     */
    public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        // add a few extra elements in the array to ensure that we have enough keys when unserializing
        // older data which does not include all properties.
        $data = array_merge($data, array_fill(0, 2, null));

        list(
            $this->password,
            $this->salt,
            $this->usernameCanonical,
            $this->username,
            $this->expired,
            $this->locked,
            $this->credentialsExpired,
            $this->enabled,
            $this->id
            ) = $data;
    }

    /**
     * Removes sensitive data from the user.
     */
    public function eraseCredentials()
    {
        $this->plainPassword = null;
    }

    /**
     * Returns the user unique id.
     *
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getUsernameCanonical()
    {
        return $this->usernameCanonical;
    }

    public function getSalt()
    {
        return $this->salt;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getEmailCanonical()
    {
        return $this->emailCanonical;
    }

    /**
     * Gets the encrypted password.
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    /**
     * Gets the last login time.
     *
     * @return \DateTime
     */
    public function getLastLogin()
    {
        return $this->lastLogin;
    }

    public function getConfirmationToken()
    {
        return $this->confirmationToken;
    }

    /**
     * Returns the user roles
     *
     * @return array The roles
     */
    public function getRoles()
    {
        $roles = $this->roles;

        foreach ($this->getGroups() as $group) {
            $roles = array_merge($roles, $group->getRoles());
        }

        // we need to make sure to have at least one role
        $roles[] = static::ROLE_DEFAULT;

        return array_unique($roles);
    }

    /**
     * Never use this to check if this user has access to anything!
     *
     * Use the SecurityContext, or an implementation of AccessDecisionManager
     * instead, e.g.
     *
     *         $securityContext->isGranted('ROLE_USER');
     *
     * @param string $role
     *
     * @return boolean
     */
    public function hasRole($role)
    {
        return in_array(strtoupper($role), $this->getRoles(), true);
    }

    public function isAccountNonExpired()
    {
        if (true === $this->expired) {
            return false;
        }

        if (null !== $this->expiresAt && $this->expiresAt->getTimestamp() < time()) {
            return false;
        }

        return true;
    }

    public function isAccountNonLocked()
    {
        return !$this->locked;
    }

    public function isCredentialsNonExpired()
    {
        if (true === $this->credentialsExpired) {
            return false;
        }

        if (null !== $this->credentialsExpireAt && $this->credentialsExpireAt->getTimestamp() < time()) {
            return false;
        }

        return true;
    }

    public function isCredentialsExpired()
    {
        return !$this->isCredentialsNonExpired();
    }

    public function isEnabled()
    {
        return $this->enabled;
    }

    public function isExpired()
    {
        return !$this->isAccountNonExpired();
    }

    public function isLocked()
    {
        return !$this->isAccountNonLocked();
    }

    public function isSuperAdmin()
    {
        return $this->hasRole(static::ROLE_SUPER_ADMIN);
    }

    public function isUser(\FOS\UserBundle\Model\UserInterface $user = null)
    {
        return null !== $user && $this->getId() === $user->getId();
    }

    public function removeRole($role)
    {
        if (false !== $key = array_search(strtoupper($role), $this->roles, true)) {
            unset($this->roles[$key]);
            $this->roles = array_values($this->roles);
        }

        return $this;
    }

    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    public function setUsernameCanonical($usernameCanonical)
    {
        $this->usernameCanonical = $usernameCanonical;

        return $this;
    }

    /**
     * @param \DateTime $date
     *
     * @return User
     */
    public function setCredentialsExpireAt(\DateTime $date = null)
    {
        $this->credentialsExpireAt = $date;

        return $this;
    }

    /**
     * @param boolean $boolean
     *
     * @return User
     */
    public function setCredentialsExpired($boolean)
    {
        $this->credentialsExpired = $boolean;

        return $this;
    }

    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    public function setEmailCanonical($emailCanonical)
    {
        $this->emailCanonical = $emailCanonical;

        return $this;
    }

    public function setEnabled($boolean)
    {
        $this->enabled = (Boolean) $boolean;

        return $this;
    }

    /**
     * Sets this user to expired.
     *
     * @param Boolean $boolean
     *
     * @return User
     */
    public function setExpired($boolean)
    {
        $this->expired = (Boolean) $boolean;

        return $this;
    }

    /**
     * @param \DateTime $date
     *
     * @return User
     */
    public function setExpiresAt(\DateTime $date = null)
    {
        $this->expiresAt = $date;

        return $this;
    }

    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    public function setSuperAdmin($boolean)
    {
        if (true === $boolean) {
            $this->addRole(static::ROLE_SUPER_ADMIN);
        } else {
            $this->removeRole(static::ROLE_SUPER_ADMIN);
        }

        return $this;
    }

    public function setPlainPassword($password)
    {
        $this->plainPassword = $password;

        return $this;
    }

    public function setLastLogin(\DateTime $time = null)
    {
        $this->lastLogin = $time;

        return $this;
    }

    public function setLocked($boolean)
    {
        $this->locked = $boolean;

        return $this;
    }

    public function setConfirmationToken($confirmationToken)
    {
        $this->confirmationToken = $confirmationToken;

        return $this;
    }

    public function setPasswordRequestedAt(\DateTime $date = null)
    {
        $this->passwordRequestedAt = $date;

        return $this;
    }

    /**
     * Gets the timestamp that the user requested a password reset.
     *
     * @return null|\DateTime
     */
    public function getPasswordRequestedAt()
    {
        return $this->passwordRequestedAt;
    }

    public function isPasswordRequestNonExpired($ttl)
    {
        return $this->getPasswordRequestedAt() instanceof \DateTime &&
            $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
    }

    public function setRoles(array $roles)
    {
        $this->roles = array();

        foreach ($roles as $role) {
            $this->addRole($role);
        }

        return $this;
    }

    /**
     * Gets the groups granted to the user.
     *
     * @return Collection
     */
    public function getGroups()
    {
        return $this->groups ? : $this->groups = new ArrayCollection();
    }

    public function getGroupNames()
    {
        $names = array();
        foreach ($this->getGroups() as $group) {
            $names[] = $group->getName();
        }

        return $names;
    }

    public function hasGroup($name)
    {
        return in_array($name, $this->getGroupNames());
    }

    public function addGroup(\FOS\UserBundle\Model\GroupInterface $group)
    {
        if (!$this->getGroups()->contains($group)) {
            $this->getGroups()->add($group);
        }

        return $this;
    }

    public function removeGroup(\FOS\UserBundle\Model\GroupInterface $group)
    {
        if ($this->getGroups()->contains($group)) {
            $this->getGroups()->removeElement($group);
        }

        return $this;
    }

    public function __toString()
    {
        return (string) $this->getUsername();
    }


}

如果我删除扩展Baseuser(FOS\UserBundle\Model\user),它会给出错误“用户提供者必须返回一个UserInterface对象”。

然后我尝试添加“implements UserInterface,GroupableInterface”,但它仍然给出“没有用户提供程序”Acme\SecurityBundle\Entity\user“。

共有3个答案

娄学文
2023-03-14

@fosculus:属性id呢?它也在FOS\UserBundle\Model\user中定义。为什么它没有给出任何问题?

马正初
2023-03-14

我们不需要覆盖所有字段来重命名数据库中的字段,我可以通过使用AttributeOverride来实现这一点

 /**
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="Acme\SecurityBundle\Entity\UserRepository")
 * @ORM\AttributeOverrides({
 *      @ORM\AttributeOverride(name="roles",
 *          column=@ORM\Column(
 *              name     = "user_roles",
 *              type = "array"
 *          )
 *      )
 * })  
 */
    Class User extends BaseUser
    {


    ...


    }
令狐经武
2023-03-14

https://github . com/FriendsOfSymfony/fouser bundle/blob/master/Model/user . PHP

https://github . com/FriendsOfSymfony/fouser bundle/blob/master/Resources/config/doctrine/model/user . ORM . XML

属性< code>username已在< code > FOS \ User bundle \ Model \ User 中定义。它的元数据在他们的资源配置中。所以你实际上是在定义这个列两次。

 类似资料:
  • 问题内容: 我是使用Maven和JBOSS处理JPA的初学者,通过Restful使我的应用程序出现以下问题,我在进行DEPLOY 不是那一步,检查所有posles解决方案,但是没有找到任何东西,有人可以帮我吗? 提前致谢 下面,我显示了我已经完成映射的postgres中的SQL代码。 我有三个表( 活动 , 事件 和 照片 ),其中一个表( 照片 )引用了另外两个表( 活动 和 事件 ),但是在一

  • 我一直得到当尝试添加一个新项目到列表中,例如Items.add(p);你能帮助我理解为什么我得到这个例外吗?

  • 两者的区别是什么 和 它们都是编译的。

  • 问题内容: 特定实体存在映射例外。不能弄清楚问题出在哪里。我从头到尾检查了所有映射3次。我仍然收到映射异常。 发送给员工的电子邮件仅映射一次。但它仍然报告错误重复映射 错误是: 电子邮件Pojo email.hbm.xml 相关脚本 发送给员工的电子邮件仅映射一次。但它仍然报告错误重复映射 问题答案: 您是否将Employee中的集合设置为逆?

  • Serenity 提供一些映射特性,以匹配数据库的表、行的列名称。 列与表的映射约定 默认情况下,行(row)类移除 Row 后缀后,被认为匹配数据库中具有相同名称的表。 属性被认为匹配数据库中具有相同名称的列。 比方说我们有这样一个行定义: public class CustomerRow : Row { public string StreetAddress {

  • 问题内容: 我在使用JPA和Hibernate时遇到问题,但无法解决。 因此,这是我的applicationContext.xml: 这是我的表演实体: 这是我的嵌入式id类: 所以,这些是我的课程。但是,当我想运行我的应用程序时,会遇到以下异常: 我认为第一个例外是由第二个例外引起的。那么,为什么我会得到“实体映射中的重复列?”。使用嵌入式id类是个好主意吗? 问题答案: 你的两个变量,并在你的