如何避免在 Java 中具有相同方法主体但不同 return 类型的重复代码?

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

想法:

当我使用 hibernate 时,我发现每次我都必须编写某种代码。所以我将它们作为包装器移动到另一种方法。哪里会有功能接口作为参数,这样我就可以在这些上下文方法中附加一些代码。

问题:

这是我的两种方法。一个 returns 对象,而另一个正在返回列表。我怎样才能准确地泛化这两种方法并将其作为一个方法来避免代码重复。

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;
}

为了更好的理解,这是我的全部class。如果有人可以建议我更好的方法,我将非常感激。我最近几天一直在研究这个。

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();
        }
    }
}

稍后我在 BaseDaoImpl.java 中扩展了 QueryExecutionContext。所以我需要知道两件事。

  1. 我的做法好不好。我使用的是纯休眠模式,仅此而已。此处没有 spring 引导。
  2. 如果是,请告诉我如何解决 objectReturnContext() 和 listReturnContext() 方法中的代码重复问题。

Object/List<T> 参数可以是通用参数 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 将根据您传递给方法的内容 function 进行推断。如果你这样称呼它:

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

那么U就是Object.

如果你这样称呼它:

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

那么U就是ArrayList<T>.