How can I avoid duplicate code with the same method body but different return types in Java?

Farhat Shahir

The Idea:

When I was using hibernate I saw that everytime I had to write some sort of code. So I moved them to another method as wrapper. Where there will be functional interface as argument so that I can append some code in those context methods.

Problem:

Here is my two methods. One returns Object while another one is returning List. How can I exactly generify and make those two methods as one so that I can avoid code duplication.

public Object objectReturnContext(Function<Session, Object> function) {
    Object object = null;
    Transaction transaction = null;

    try {
        Session session = HibernateUtil.sessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        object = function.apply(session);
        transaction.commit();
    } catch (NoResultException exception) {
        if (transaction != null) transaction.rollback();
        return object;
    } catch (HibernateException exception) {
        if (transaction != null) transaction.rollback();
        exception.getStackTrace();
    }

    return object;
}


public List<T> listReturnContext(Function<Session, List<T>> function) {
    List<T> object = null;
    Transaction transaction = null;

    try {
        Session session = HibernateUtil.sessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        object = function.apply(session);
        transaction.commit();
    } catch (NoResultException exception) {
        if (transaction != null) transaction.rollback();
        return object;
    } catch (HibernateException exception) {
        if (transaction != null) transaction.rollback();
        exception.getStackTrace();
    }

    return object;
}

For better understanding, This is my whole class. If anyone can advice me any better way I will be very thankful. I have been into this for last few days.

package com.go_task.database;


import javax.persistence.Table;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;


public abstract class QueryExecutionContext <T> {

    public Class<T> entity;
    public String tableName;

    public QueryExecutionContext(Class<T> entity) {
        this.entity = entity;
        this.tableName = entity.getAnnotation(Table.class).name();
    }

    public List<T> criteriaContext(CriteriaContextRunner<Session, Root<T>,
            CriteriaQuery<T>, CriteriaBuilder, List<T>> runner) {
        List<T> data = new ArrayList<>();
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.sessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
            CriteriaQuery<T> criteriaQuery =
                    criteriaBuilder.createQuery(entity);
            Root<T> root = criteriaQuery.from(entity);
            data = runner.apply(session, root, criteriaQuery, criteriaBuilder);
            transaction.commit();
        } catch (HibernateException exception) {
            if (transaction != null) transaction.rollback();
            exception.getStackTrace();
        }

        return data;
    }

    public Object singleCriteriaContext(CriteriaContextRunner<Session, Root<T>,
            CriteriaQuery<T>, CriteriaBuilder, Object> runner) {
        Object data = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.sessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
            CriteriaQuery<T> criteriaQuery =
                    criteriaBuilder.createQuery(entity);
            Root<T> root = criteriaQuery.from(entity);
            data = runner.apply(session, root, criteriaQuery, criteriaBuilder);
            transaction.commit();
        } catch (HibernateException exception) {
            if (transaction != null) transaction.rollback();
            exception.getStackTrace();
        }

        return data;
    }

    public Object objectReturnContext(Function<Session, Object> function) {
        Object object = null;
        Transaction transaction = null;
    
        try {
            Session session = HibernateUtil.sessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            object = function.apply(session);
            transaction.commit();
        } catch (NoResultException exception) {
            if (transaction != null) transaction.rollback();
            return object;
        } catch (HibernateException exception) {
            if (transaction != null) transaction.rollback();
            exception.getStackTrace();
        }
    
        return object;
    }
    
    public List<T> listReturnContext(Function<Session, List<T>> function) {
        List<T> object = null;
        Transaction transaction = null;
    
        try {
            Session session = HibernateUtil.sessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            object = function.apply(session);
            transaction.commit();
        } catch (NoResultException exception) {
            if (transaction != null) transaction.rollback();
            return object;
        } catch (HibernateException exception) {
            if (transaction != null) transaction.rollback();
            exception.getStackTrace();
        }
    
        return object;
    }

    public void noReturnContext(Consumer<Session> consumer) {
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.sessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            consumer.accept(session);
            transaction.commit();
        } catch (HibernateException exception) {
            if (transaction != null) transaction.rollback();
            exception.getStackTrace();
        }
    }
}

I have extented QueryExecutionContext in my BaseDaoImpl.java later on. So I need to know 2 things.

  1. Is my approch is ok or not. Im using pure hibernate and nothing else. No spring boot here.
  2. If so then tell me how can I solve the code duplication in objectReturnContext() and listReturnContext() method.

Thanks in advance!

Sweeper

The Object/List<T> parameter could be a generic parameter U:

public <U> U returnContext(Function<Session, U> function) {
    U object = null;
    Transaction transaction = null;

    try {
        Session session = HibernateUtil.sessionFactory().getCurrentSession();
        transaction = session.beginTransaction();
        object = function.apply(session);
        transaction.commit();
    } catch (NoResultException exception) {
        if (transaction != null) transaction.rollback();
        return object;
    } catch (HibernateException exception) {
        if (transaction != null) transaction.rollback();
        exception.getStackTrace();
    }

    return object;
}

U will be inferred depending on what function you pass into the method. If you call it like:

Object o = returnContext(s -> {
    ...
    return new Object(); // just an example
});

Then U is Object.

If you call it like:

List<T> list = returnContext(s -> {
    ...
    return new ArrayList<T>(); // just an example
});

Then U is ArrayList<T>.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to avoid duplicate code when writing the body to a interface method?

From Dev

In Java, how can I return two different types based on an argument?

From Dev

Can I return two array types at the same time in a single method (LDL^T Factroization) in Java

From Dev

Can I return two array types at the same time in a single method (LDL^T Factroization) in Java

From Dev

Can I Return Different Types From An Extension Method

From Dev

How can I avoid the duplicate code of mapping in Spring project?

From Java

How do I avoid a useless return in a Java method?

From Dev

How do I avoid a useless return in a Java method?

From Dev

Generic method that can return different types

From Dev

Can a method be able to return different data types?

From Dev

Generic method that can return different types

From Dev

Avoid multiple definitions of a class for different types containing the same method

From Dev

How can I write a method to easily create different types of subclasses

From Dev

How can I avoid duplicate templates in Meteor?

From Dev

How can I avoid duplicate items in a checkListBox

From Dev

Consuming an API which has a two types which are the same but have different names. How can I reuse my code?

From Dev

How to Inherit a method with different generic return types

From Dev

How can I test with rspec different routes but to the same controller method?

From Dev

Scala trait same method and argument with different return types

From Dev

How attoparsec can return values of different types?

From Dev

Have too many return statements within method according to Java checkstyle, how can I simplify my code to comply with the 2 return maximum?

From Dev

How to abstract different return types in Java?

From Dev

How to abstract different return types in Java?

From Dev

How can two different types implement the same method in golang using interfaces?

From Dev

How can I duplicate different rows in Excel?

From Dev

How can I duplicate different rows in Excel?

From Dev

How can I avoid naming my variables the same thing as my method names in ruby?

From Dev

Can I create an ArrayList of different types in Java

From Dev

Can I create an ArrayList of different types in Java

Related Related

  1. 1

    How to avoid duplicate code when writing the body to a interface method?

  2. 2

    In Java, how can I return two different types based on an argument?

  3. 3

    Can I return two array types at the same time in a single method (LDL^T Factroization) in Java

  4. 4

    Can I return two array types at the same time in a single method (LDL^T Factroization) in Java

  5. 5

    Can I Return Different Types From An Extension Method

  6. 6

    How can I avoid the duplicate code of mapping in Spring project?

  7. 7

    How do I avoid a useless return in a Java method?

  8. 8

    How do I avoid a useless return in a Java method?

  9. 9

    Generic method that can return different types

  10. 10

    Can a method be able to return different data types?

  11. 11

    Generic method that can return different types

  12. 12

    Avoid multiple definitions of a class for different types containing the same method

  13. 13

    How can I write a method to easily create different types of subclasses

  14. 14

    How can I avoid duplicate templates in Meteor?

  15. 15

    How can I avoid duplicate items in a checkListBox

  16. 16

    Consuming an API which has a two types which are the same but have different names. How can I reuse my code?

  17. 17

    How to Inherit a method with different generic return types

  18. 18

    How can I test with rspec different routes but to the same controller method?

  19. 19

    Scala trait same method and argument with different return types

  20. 20

    How attoparsec can return values of different types?

  21. 21

    Have too many return statements within method according to Java checkstyle, how can I simplify my code to comply with the 2 return maximum?

  22. 22

    How to abstract different return types in Java?

  23. 23

    How to abstract different return types in Java?

  24. 24

    How can two different types implement the same method in golang using interfaces?

  25. 25

    How can I duplicate different rows in Excel?

  26. 26

    How can I duplicate different rows in Excel?

  27. 27

    How can I avoid naming my variables the same thing as my method names in ruby?

  28. 28

    Can I create an ArrayList of different types in Java

  29. 29

    Can I create an ArrayList of different types in Java

HotTag

Archive