What is need of Hibernate Custom Result Transformer?

Hibernate provide AliasToBean result transformer, it will be converted into Bean list which is provided by use but some time its not enough, We need to implement our own logic to convert result into Object too complete this requirement hibernate provide Custom Transformer.Custom Transefmer extends AliasedTupleSubsetResultTransformer and we need to override transformTuple method, For each record transformTuple method will be called by hibernate, transformTuple we can write our own logic to convert object according to our convince. Example: We create an example, i.e We want to hide name of Employee if it’s name is “admin”, so here example of that customTransformer as bellow:

CustomTransformer.java

package com.javadeveloperzone.transformer;

import com.javadeveloperzone.model.Employee;
import org.hibernate.transform.AliasedTupleSubsetResultTransformer;


/**
 * Created by Subhash Lamba on 12-03-2017.
 */
public class CustomTransformer extends AliasedTupleSubsetResultTransformer {

    public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
        return true;
    }

    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {

        if (tuple[0] instanceof Employee) {
            if (("admin".equalsIgnoreCase(((Employee) tuple[0]).getEmployeeName()))) {
                ((Employee) tuple[0]).setEmployeeName("HIDE NAME");
            }
        }
        return tuple[0];
    }
}

How to use Custom Transformer:

@Override
   public List<Employee> list() {
       return (List<Employee>)sessionFactory.getCurrentSession().createCriteria(Employee.class).setResultTransformer(new CustomTransformer()).list();
   }

 

Output:

Hibernate Custom Result Transformer Ouput

Hibernate Custom Result Transformer Output

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *