【问题标题】:Grails domain-classes mapping in one-to-one relation一对一关系中的 Grails 域类映射
【发布时间】:2013-11-10 11:33:03
【问题描述】:

我已经准备好数据库表架构,我需要在我的 Grails 应用程序中使用它。

我在 PostgreSQL 中的表:

CREATE TABLE "user" (
  id serial NOT NULL,
  login character varying(32) NOT NULL,
  password character varying(32) NOT NULL,
  email character varying(255) NOT NULL,
  date_created time with time zone NOT NULL DEFAULT now(),
  last_updated time with time zone NOT NULL DEFAULT now(),
  is_banned boolean DEFAULT false,
  CONSTRAINT "PK_user_id" PRIMARY KEY (id),
  CONSTRAINT "UN_user_email" UNIQUE (email),
  CONSTRAINT "UN_user_login" UNIQUE (login)
)

CREATE TABLE profile (
  "user" integer NOT NULL DEFAULT nextval('profile_id_seq'::regclass),
  first_name character varying(25) NOT NULL,
  middle_name character varying(25) NOT NULL,
  last_name character varying(25) NOT NULL,
  address integer,
  CONSTRAINT "PK_PROFILE_user" PRIMARY KEY ("user"),
  CONSTRAINT "FK_PROFILE_user_USER_id" FOREIGN KEY ("user")
      REFERENCES "user" (id) MATCH SIMPLE
      ON UPDATE RESTRICT ON DELETE CASCADE
)

如您所见,“profile”表有主键,这也是它的外键。这是 geails 映射问题的主要“特征”。

我的表映射到 grails 域类的实现:

class User {
    ...
    static hasOne = [profile : Profile];
    ...
}

class Profile {
    ...
    User user;
    ...
    static mapping = {
        id name: 'user'
        version false
        address column: 'address'
        user column: '`user`'
    };
    ...
}

此类映射崩溃异常:

Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: ru.redlisa.model.User, at table: profile, for columns: [org.hibernate.mapping.Column(user)]
  1. 如何正确地将表映射到 grails 域类?

  2. 如何获取交互界面?

像这样:

User user = new User();
user.addToProdile(new Profile());

或者

new User(profile: new Profile()).save();

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    您可以尝试使用这种方法:

    class User {
    ...
    Profile profile
    ...
    static mapping = {
        id column: 'user', generator: 'foreign', params: [ property: 'profile']
        ...
        }
    }
    

    【讨论】:

    • 那么 Profile 类呢?我应该保持不变吗?
    【解决方案2】:

    非常感谢araxn1d 展示了外国发电机的正确方式。我已经像这样重写了我的域:

    class User {
        ...
        static hasOne = [profile : Profile];
        ...
    }
    
    class Profile {
        ...
        static belongsTo = [address: Address,
                            user:    User];
        ...
        static mapping = {
            id column: '`user`', generator: 'foreign', params: [ property: 'user']
            version false
            address column: 'address'
            user column: '`user`', insertable: false, updateable: false
        };
        ...
    }
    

    它有效!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多