Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm assuming you are talking about mapping a String primary key (normally a natural key) to the primary key in a grails domain object.</p> <p>This answer is derived from information found here: <a href="http://dsommerville.blogspot.com/2009/09/mapping-natural-keys-using-gorm.html" rel="nofollow">http://dsommerville.blogspot.com/2009/09/mapping-natural-keys-using-gorm.html</a> and here: <a href="http://gr8fanboy.wordpress.com/2010/04/08/adding-a-natural-key-to-a-database-table-using-straight-gorm/" rel="nofollow">http://gr8fanboy.wordpress.com/2010/04/08/adding-a-natural-key-to-a-database-table-using-straight-gorm/</a></p> <p>For example, you have a table Users defined with the following schema:</p> <pre><code>username varchar(40) not null pimary key, firstname varchar(40) not null, lastname varchar(40) not null </code></pre> <p>To do this in grails, you have to massage the definition a little.' First, you have to map the id to the given column in your database. With a generator "assigned"</p> <p>Then, for usability, you may want to add the transient field username so that you can use user.username = . Otherwise, I believe you'd have to access the field using id. The getter and setter for this transient property set the appropriate "id" field, which in turn updates the database.</p> <pre><code>class User { String id String password String fullName static transients = ['username'] static constraints = { id(unique:true,blank:false) password(nullable:true,maxSize:20) fullName(nullable:true,maxSize:20) } static mapping = { table 'users' id column: 'username', generator: 'assigned' version false } // void setUsername(String username) { id = username } String getUsername() { return id } } </code></pre> <p>Note: Scaffolding doesn't recognize the transient field, so you'll have to work the generated controllers/views if you want your code to more closely model your db.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload