Grails域类以一对一的关系映射

Art*_*Lab 1 grails grails-orm

我已准备好数据库表架构,我需要在我的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
)
Run Code Online (Sandbox Code Playgroud)

如您所见,"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`'
    };
    ...
}
Run Code Online (Sandbox Code Playgroud)

此类映射崩溃与异常:

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)]
Run Code Online (Sandbox Code Playgroud)
  1. 如何正确地将表映射到grails域类?

  2. 如何获得交互界面?

像这样:

User user = new User();
user.addToProdile(new Profile());
Run Code Online (Sandbox Code Playgroud)

要么

new User(profile: new Profile()).save();
Run Code Online (Sandbox Code Playgroud)

rxn*_*n1d 6

您可以尝试使用此方法:

class User {
...
Profile profile
...
static mapping = {
    id column: 'user', generator: 'foreign', params: [ property: 'profile']
    ...
    }
}
Run Code Online (Sandbox Code Playgroud)