java - hibernate 和 thrift 之间的转换

标签 java generics

这与 hibernate 和 thrift 本身无关。

我正在开发一个 Java 应用程序,我通过 Hibernate 从数据库获取数据,并希望通过 apache thrift 服务来提供这些对象。到目前为止,我只有几个模型,但对于每个模型,我都必须迭代 hibernate 对象列表并构造 thrift 对象列表。

例如,考虑以下代码片段(这是 thrift 服务处理程序,它将 hibernate 集合作为 IN 并返回 thrift 集合):

@Override
public List<TOutcome> getUserOutcomes(int user_id) throws TException {
    List<Outcome> outcomes = this.dataProvider.getOutcomesByUserId(user_id);
    List<TOutcome> result = new ArrayList<>();
    for (Iterator iterator = outcomes.iterator(); iterator.hasNext();) {
        Outcome outcome = (Outcome) iterator.next();
        TOutcome t_outcome = new TOutcome(
                (double) (Math.round(outcome.getAmount() * 100)) / 100,
                outcome.getUser().getName(),
                String.valueOf(outcome.getCategory().getName()));
        t_outcome.setComment(outcome.getComment());
        result.add(t_outcome);
    }
    return result;
}

@Override
public List<TIncome> getUserIncomes(int user_id) throws TException {
    List<Income> incomes = this.dataProvider.getIncomesByUserId(user_id);
    List<TIncome> result = new ArrayList<>();
    for (Iterator iterator = incomes.iterator(); iterator.hasNext();) {
        Income income = (Income) iterator.next();
        TIncome t_income = new TIncome(
                (double) (Math.round(income.getAmount() * 100)) / 100,
                income.getUser().getName(),
                String.valueOf(income.getCategory().getName()));
        t_income.setComment(income.getComment());
        result.add(t_income);
    }
    return result;
}

OutcomeIncome - 这些是 Hibernate 带注释的类,TOutcomeTIcome - 是相关的 thrift 对象(共享 80-90% 的字段)。

现在违反了“DRY”原则,因为这段代码非常非常相似。我想提供一种通用方法来迭代 hibernate 对象并返回 thrift 对象。我正在考虑泛型和设计模式。

在动态语言中,我可以只使用字符串来构建类名和构造对象(没有类型检查)。我想有可能在 Java 中使用泛型做类似的事情,但我不确定应该从哪里开始。

最佳答案

据我所知,只有大约 10 行代码是常见的,而且它们的常见是偶然的,而不是业务需求。当然,您可以重构代码以提取一些接口(interface):一个供数据提供者在 getOutcomesByUserId 之间进行选择。和getIncomesByUserId ,另一个对象工厂 - 要么 new TIncomenew TOutcome 。或者使用反射。然而,这些代码变体看起来会更加复杂并且更难支持。我认为目前已经足够好了,不值得改变。期待更好的使用for(Income income : incomes)而不是迭代器样板。

但是,如果您有复杂但相似的数据结构要映射,那么有些库可以显着简化映射,例如看看Dozer .

关于java - hibernate 和 thrift 之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15681009/

相关文章:

java - 如何可视化缺失的内面板?

java - 比较两个时间在java中是更大还是更小

java - 是Java Jackson ObjectWriter.ObjectWriter.writeValueAsString(obj);稳定的?

java - 关于使用pathconvert Ant 任务的一些疑问。它做什么?

java - 如何在 Java 中调用 AutoIT UDF

java - 在 hashmap 中一般实现方法中传递参数

C#类声明中泛型参数的重复

java - 通用静态工厂方法问题

.net - 定义具有相同名称和不同数量类型参数的泛型类 (C++/CLI)

c# - 如何获取给定方法的泛型参数的类型