Blob User Type in Hibernate

I’ve used this same user type in a few projects:

package ca.intelliware.util.hibernate;

import java.io.IOException;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;

public class BinaryUserType extends BaseHibernateUserType {

  public int[] sqlTypes() {
    return new int[] { Types.BLOB };
  }

  public Class returnedClass() {
    return byte[].class;
  }

  public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
     throws HibernateException, SQLException {
    Blob blob = resultSet.getBlob(names[0]);
    try {
      return blob.getBytes(1, (int) blob.length());
    } catch (IOException e) {
      throw new HibernateException(e);
    }
  }

  public void nullSafeSet(PreparedStatement statement, Object value, int index)
      throws HibernateException, SQLException {
    try {
      statement.setBlob(index, value);
    } catch (IOException e) {

    }
  }

  public Object deepCopy(Object value) {
    if (value == null) {
      return null;
    } else {
      byte[] bytes = (byte[]) value;
      byte[] result = new byte[bytes.length];
      System.arraycopy(bytes, 0, result, 0, bytes.length);
      return result;
    }
  }

  public boolean isMutable() {
    return true;
  }
}

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply