5

I've ran into an issue while trying to put together a Grails app with an AS400/DB2 database. I cannot get most of the files mapped because they do not have a unique field to use as an id. And even if they do they are a text based field and not in a format that could be converted to a long type. (I don't get why the PK has to be a long data type? If you wanted to us a sequence or AI for the pk that would make sense but what if you just needed a unique key? Am I missing something here?)

I'm wondering if it is possible to keep the datasource that I have set up and just use it for straight SQL access to the DB without having to use domain objects?

Something I've seen was setting the domain object as transient. But I don't know if you could still do something like that without an id field. Anybody know how that works?

Any ideas?

Thanks, Jon

jonsinfinity
  • 187
  • 3
  • 16

2 Answers2

3

There's no requirement that a primary key be long, it's just the standard for Hibernate and Grails. You can treat a varchar column that's unique as the primary key with a domain class like this:

class Person {

   String username
   String firstName
   String lastName

   static mapping = {
      id name: 'username', generator: 'assigned'
      version false
   }
}

This works for a table defined by this DDL:

create table person (
   username varchar(255) not null,
   first_name varchar(255) not null,
   last_name varchar(255) not null,
   primary key (username)
);

I added 'version false' since it's a legacy system and you probably don't have a 'version' optimistic locking column.

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
3

You can access the database quite easily, we are doing the same in certain cases for performance reasons:

class SomeService {
    def dataSource;

    def nativeAccessMethod = {
        def sql = new Sql(dataSource);
        def rows = sql.rows("select * from myTable");
        /* processing continues ...*/
    }
}

Groovy's native SQL support is also nice.

Gregor Petrin
  • 2,891
  • 1
  • 20
  • 24