I am trying to create an Entity that has a byte[12] id in hibernate. It seems like it does not like to have a byte[] as a primary key and as another column it sets it up as a tinyblob in the backing mysql db. I have tried to create a String, but the problem is that the string in java is 2 bytes per char, while it is one byte per char in mysql. I’m looking for something like this
@Entity
public class TestClass {
@Id
@Column(length=12)
private byte[] id;
...
to map to a mysql table like this
Table 'testclass'
Column id - varbinary length 12 primary key
...
I have tried a number of different ways (primarily trying to fiddle with Strings) to do this but it does not seem to work right. Has anyone been able to do this already? Thanks.
As you experienced, this is not supported by standard JPA. From the specification:
That being said, it appears that you could use a wrapper type around the
byte[]and implement a custom user type. The UserType for a byte[] identifier property wiki page provides an implementation.Refer to the section 2.4.3.2. Type of the Hibernate Annotations documentation to declare and use this custom type with annotations.
References
Resource