问题
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.
回答1:
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.
回答2:
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.
回答3:
You can also map your UUID to a BigInteger (java.sql.Types.BIGINT) in your UserType if you don't care about how your UUID is represented in your database (in this case, it will be represented in base 10).
来源:https://stackoverflow.com/questions/2007013/hibernate-usertype-and-a-defined-length