views:

177

answers:

2

I have a hibernate Usertype something like this:

public class UUIDHibernateType implements UserType
{
    private static final int[] SQL_TYPES = new int[] { Types.CHAR };

    public int[] sqlTypes ()
    {
        return SQL_TYPES;
    }

    // ...
}

The problem I have is, that hibernate generates a sql script with the types CHAR(1) which is not correct, I would actually need CHAR(36). How would I define the default length of a custom type?

For the moment I'm stuck with defining the sql-type like this:

<id name="id"
    type="org.openscada.ae.server.storage.jdbc.internal.UUIDHibernateType">
    <column name="ID" length="36" sql-type="CHAR(36)" not-null="true" />
    <generator class="assigned" />
</id>

It shouldn't be a problem in this case, but how would I do it if the need arises?

PS: If someone has a better idea how to handle UUIDs transparently and database agnostig, I'm grateful.

A: 

I suggest to use the built-in UUID generator of Hibernate (see the docs). Hibernate should then figure out the correct mapping and size, etc. of the PK column.

Aaron Digulla
this is not an option, I have to provide the id by myself, because it needs to be created before the object is saved (the actual saving happens asynchronously).
Mauli
In that case, look at the source code of the UUID generator how it specifies the column size.
Aaron Digulla
that is definitely an idea, I will have a look, but I guess I will find it somewhere in each dialect implementation, because uuids and guids are not natively available in any database.
Mauli
A: 

The code returned by UserType.sqlTypes is used in the Dialect to look up the registered type. So if you have sqlTypes return a code that isn't already in use, you can subclass your Dialect and register that code as a char(36). For example:

// in your custom type public int[] sqlTypes() { return new int[] { 1337 }; }

// in your custom dialect registerColumnType(1337, "char(36)")

I haven't tried it, but it's been reported to work on the Hibernate forums.

Brian Deterling
sounds good in principle, but I can't subclass the dialect, because the user (implementor) should be able to specify it's own dialect, without having to worry about the mapping at all. But I will have a look if it is possible to add this type within the session factory.
Mauli