Reputation: 13372
I have two domain classes and want to have one-to-one BIDIRECTIONAL relation between them. I write:
class Person {
Book book;
String name
Integer age
Date lastVisit
static constraints = {
book unique: true // "one-to-one". Without that = "Many-to-one".
}
}
class Book {
String title
Date releaseDate
String ISBN
static belongsTo = [person:Person] // it makes relationship bi-directional regarding the grails-docs
}
So, i want to have bi-directional, i could NOT find link from Book to Person in generated SQL:
CREATE TABLE `book` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`isbn` varchar(255) NOT NULL,
`release_date` datetime NOT NULL,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
So then it means it is not bidirectional then? How to make bidirectional?
Upvotes: 1
Views: 5685
Reputation: 205
To make this relationship one to one bidirectional,you should define them as fallows
//Person is the owning side of relationship
class Person {
//a foreign key will be stored in Book table called person_id
static hasOne = [book:Book]
static constraints = {
book unique: true
}
}
Class Book{
Person person
}
belongsTo is used for specifying the owner side(which manages relationship) of a one-to-many, many-to-one, or many-to-many relationship and for making relationship bidirectional
belongsTo should be used always in owned side
Upvotes: 1
Reputation: 1289
check out the hasOne property, in which class you define hasOne and belongsTo depends on where you want the FK to be stored, check this grails doc regarding hasOne: http://www.grails.org/doc/latest/ref/Domain%20Classes/hasOne.html
Upvotes: 3