gpt4 book ai didi

java - hibernate 和 thrift 之间的转换

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:27 24 4
gpt4 key购买 nike

这与 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com