gpt4 book ai didi

java - 它如何将一个对象字段数据复制到同一类的另一个对象?

转载 作者:行者123 更新时间:2023-12-01 13:58:46 29 4
gpt4 key购买 nike

在问题的上下文中,类别表有两行映射到股票。但是当我应用下面的逻辑时,我在结果中只得到一行条目。

为了解决我想知道如何将对象属性复制到同一类的新创建的对象? 这样新创建的对象将具有旧对象的数据。

public class App {
public static void main(String[] args) {
System.out.println("Hibernate many to many (XML Mapping)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();

try {
List<Stock> stocksNew=new ArrayList<Stock>();
List<Stock> stocks = session.createQuery("FROM Stock").list();

for (Stock stock:stocks) {
Set<Category> categories = stock.getCategories();

if (categories.isEmpty())
{
System.out.println("true");
stocksNew.add(stock);
}
else
{
for (Iterator<Category> iterator2 =
categories.iterator(); iterator2.hasNext();) {
Category category = (Category) iterator2.next();
stock.
stock.setCategoryId(category.getCategoryId());
stock.setName(category.getName());
stocksNew.add(stock);

}
}
}

for (Stock stock : stocksNew) {
System.out.println("Stock ID: " + stock.getStockId());
System.out.println("Stock Name: " + stock.getStockName());
System.out.println("Stock Code: " + stock.getStockCode());
System.out.println("Category Id:"+stock.getCategoryId());
System.out.println("Category Name:"+stock.getName());
}


} catch (HibernateException e) {
e.printStackTrace();
} finally {
session.close();
}
}

}

输出

Stock ID: 1
Stock Name: PADINI
Stock Code: 7052
Category Id:2
Category Name:INVESTMENT
Stock ID: 1
Stock Name: PADINI
Stock Code: 7052
Category Id:2
Category Name:INVESTMENT

我得到了上述输出,但根据我的要求,输出应该以以下方式出现

Stock ID: 1
Stock Name: PADINI
Stock Code: 7052
Category Id:1
Category Name:CONSUMER
Stock ID: 1
Stock Name: PADINI
Stock Code: 7052
Category Id:2
Category Name:INVESTMENT

最佳答案

要将属性从一个 Java 对象复制到另一个 Java 对象,我建议您查看 Java bean 映射器,例如 orikaDozer 。它们可以为您节省大量代码,并且可以很好地自动执行此任务。

关于java - 它如何将一个对象字段数据复制到同一类的另一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19468803/

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