如何在GORM中使用外键而非域对象进行关联映射?
Mapping User-Organization Relationship with Hibernate in Grails
Yep, this approach works perfectly for setting up a many-to-one association between User and Organization using Grails' Hibernate-backed ORM. Let me walk through what makes this setup solid:
- Clear Relationship Definition: You’ve established that multiple users can belong to a single organization by adding the
Organizationfield directly to theUserclass—this is intuitive and aligns with how Hibernate handles associations. - Custom Schema Alignment: The
static mappingblocks let you override default table/column names to match your existing database structure, which is super handy if you’re working with a pre-built schema. - Controlled Primary Keys: Using
generator:'assigned'tells Hibernate you’ll manage the primary key values yourself, instead of relying on auto-generated IDs—great for scenarios where you have existing ID values to use. - Explicit Foreign Key Mapping: The
organization column: 'organization_Id'line explicitly ties theUserclass’s organization field to the foreign key column in theusertable, removing any ambiguity for Hibernate.
Here’s the clean, formatted code for reference:
class User { String id String firstName Organization organization static mapping = { table 'user' id column: "user_id", generator:'assigned' organization column: 'organization_Id' } } class Organization { String id String name String address static mapping = { table 'organization' id column: "organization_id", generator:'assigned' } }
With this setup, Hibernate will handle all the heavy lifting: lazy loading organizations when needed, persisting the foreign key correctly when saving users, and letting you query users with their associated organizations effortlessly.
内容的提问来源于stack exchange,提问作者Spark323
相关产品推荐
相关产品推荐

