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 sometimes it’s not enough, We need to implement our own logic to convert the result into Object too complete this requirement hibernate provide Custom Transformer.Custom Transformer 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 the name of Employee if its name is “admin”, so here example of that customTransformer as below:

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

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags:

Leave a Reply

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