gpt4 book ai didi

java - 如果记录不存在,则 Hibernate 插入

转载 作者:行者123 更新时间:2023-11-30 11:29:09 26 4
gpt4 key购买 nike

我如何使用 Hibernate 执行此操作 - 如果记录不存在,请插入它。

我有以下列

Id(主键),股票代码,代码名称,行业,部门,最后更新

如果字符串存在,我想检查 Ticker Symbol Column 的记录,如果不存在则不执行任何操作,然后插入一个新行,其中包含 Id、Ticker Symbol、Ticker Name、Industry、Sector 和 Update Date(今天的日期)。

我已经使用下面的代码创建了一个新表。

//Hibernate Create a Session Factory    
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
for (int i = 0; i < Bloomberg.getTickerSymbol().size(); i++){

//Hibernate to store Stock Tickers Data
tickerInfo.setTickerSymbol(Bloomberg.getTickerSymbol().get(i)); //Symbol
tickerInfo.setTickerName(Bloomberg.getTickerName().get(i)); //Name
tickerInfo.setTickerSector(Bloomberg.getTickerSector().get(i)); //Sector
tickerInfo.setTickerIndustry(Bloomberg.getTickerIndustry().get(i)); //Industry
tickerInfo.setTickerLastUpdate(Calendar.getInstance().getTime()); //Update Date

org.hibernate.Session session = sessionFactory.openSession();
session.beginTransaction();
session.saveOrUpdate(tickerInfo);
session.getTransaction().commit();
session.close();
}

最佳答案

 //Hibernate Create a Session Factory    
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
for (int i = 0; i < Bloomberg.getTickerSymbol().size(); i++){

//Hibernate to store Stock Tickers Data
tickerInfo.setTickerSymbol(Bloomberg.getTickerSymbol().get(i)); //Symbol
tickerInfo.setTickerName(Bloomberg.getTickerName().get(i)); //Name
tickerInfo.setTickerSector(Bloomberg.getTickerSector().get(i)); //Sector
tickerInfo.setTickerIndustry(Bloomberg.getTickerIndustry().get(i)); //Industry
tickerInfo.setTickerLastUpdate(Calendar.getInstance().getTime()); //Update Date

org.hibernate.Session session = sessionFactory.openSession();
List tickerInfos = session.createCriteria(TickerInfo.class).add(Restrictions.eq("tickerSymbol", Bloomberg.getTickerSymbol().get(i))).list();
if(tickerInfos.size()<1){
session.beginTransaction();
session.saveOrUpdate(tickerInfo);
session.getTransaction().commit();
}
}
session.close();

关于java - 如果记录不存在,则 Hibernate 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18558618/

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