问题
I have ready database table schema and I need use it in my Grails app.
My tables in 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
)
As you can see, "profile" table has primary key, which is its foreign key too. This is main "feature" with which the problems with geails mapping.
My implementation of tables mapping to grails domain classes:
class User {
...
static hasOne = [profile : Profile];
...
}
class Profile {
...
User user;
...
static mapping = {
id name: 'user'
version false
address column: 'address'
user column: '`user`'
};
...
}
This class mapping crash with exception:
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)]
How to correctly map the tables to grails domain-classes?
How to get interaction interface?
like this:
User user = new User();
user.addToProdile(new Profile());
Or
new User(profile: new Profile()).save();
回答1:
You could try to use this approach:
class User {
...
Profile profile
...
static mapping = {
id column: 'user', generator: 'foreign', params: [ property: 'profile']
...
}
}
回答2:
Big thanks to araxn1d for showing right way with foreign generator. I've rewrite my domains like this:
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
};
...
}
and it works!
来源:https://stackoverflow.com/questions/19889201/grails-domain-classes-mapping-in-one-to-one-relation