在问题的上下文中,Category 表有两行映射到 Stock。但是当我应用下面的逻辑时,我只得到一个行条目。
为了解决这个问题,我想知道如何将对象属性复制到同一类的新创建对象?这样新创建的对象将具有旧对象的数据。
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