1

我已经准备好数据库表模式,我需要在我的 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();
4

2 回答 2

6

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

class User {
...
Profile profile
...
static mapping = {
    id column: 'user', generator: 'foreign', params: [ property: 'profile']
    ...
    }
}
于 2013-11-10T20:49:56.623 回答
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
    };
    ...
}

它有效!

于 2013-11-11T06:59:10.527 回答