One-to-one association is not widely used in development, but I think it is necessary to master the following. One-to-one association has a table with a foreign key, the referenced primary key is generally the primary key of the primary table. Grails also provides good support for one-to-one associations, and the configuration is extremely simple. Grails configuration can have the following three options:
class Face { Nose nose}class Nose {}
This is a one-way Association, and the following is a two-way Association, but it cannot be updated in cascade mode.
class Face { Nose nose}class Nose {Face face}
Next, I think this is easy to use, and it can be stored and updated in the level of warranty.
class Face { Nose nose}class Nose {static belongsTo = [face:Face]}
If one-way Association is used and the level-level joint guarantee and update are used, we recommend that you use the following
class Face { Nose nose}class Nose {static belongsTo = Face}
The following is my example. I am using the third type. In this case, bidirectional association can also be used for level-based joint guarantee and update.
1. Create a domain object
class PersonInfo { Integer id; String name; CardInfo card; static mapping = { table 'm_person' card column: 'cardId' }}
class CardInfo { Integer id; String birthday; static belongsTo = [person:PersonInfo] static mapping = { table 'm_card' }}
Person is the master table, and card is the slave table, which is somewhat different from hibernate.
2. Use the Controller to cascade the storage of person and card
@ Transactional def savePersonAndCard () {def p = new PersonInfo () p. setName ("caiyil") def c = new CardInfo () c. setBirthday ("2008-01-03") p. setCard (c) p. save () render "data saved successfully "}
I have also written a method to obtain the birthday of a person.
// Query birthday def queryPersonBirthday () {def personId = params. id def p = PersonInfo. get (personId) render p. getCard (). getBirthday ()} through person ()}
Grails supports many-to-many operations, but remember that many-to-many operations require one party to maintain the association. For details, refer to grails development documentation.