How to map byte[] to jdbc BINARY type?


#1

I used hibernate 5.2.12 with mysql database.

I have following class (simplified):

@Embeddable
@Access( AccessType.FIELD )
public class IpAddress implements Serializable,Comparable<IpAddress>{

    @Column(name = "ip_address", length = 17)
    @Type(type = "org.hibernate.type.BinaryType")
    private byte[] ipBytes;
}

I want that ipBytes to be mapped to BINARY(17) mysql type,and i try to use @Type annotation, but there is no effect, hibernate map ipBytes to TINYBLOB.

I tried to use columnDefinition = “BINARY(17)”, and it work’s, but i don’t know is it safe to use, and also it database dependent.

Also tried UUIDBinaryType and hibenrnate map ipBytes right(to BINARY(17)), but when i try to insert there is an exception, because uuid must be 16 bytes length value.

How can i force hibernate to save ipBytes as BINARY type?


#2

It’s actually very simple.

Just create a new type by extending the org.hibernate.type.BinaryType

public class MySQLBinaryType extends BinaryType {

    public MySQLBinaryType() {
        setSqlTypeDescriptor(BinaryTypeDescriptor.INSTANCE);
    }
}

And the change your mapping to:

@Column(name = "ip_address", length = 17)
@Type(type = "com.you.package.MySQLBinaryType")
private byte[] ipBytes;

Here you can see an example on GitHub that works like a charm.