尝试使用for循环来保存/提交数据使用hibernate 4.3.11.Final with SQLite Dialect com.enigmabridge:hibernate4-sqlite-dialect
当我运行这段代码并检查Sqlite数据时,我发现它只保存了1个项目(好像只提交了一次)而且那个项目是我看到的最后一个(我生成的5个项目)在数据库中。
configureSessionFactory();
Session session = null;
Transaction tx=null;
try {
session = sessionFactory.openSession();
SyndEntry entry = null;
URL feedUrl = new URL(rssUrl);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
tx = session.beginTransaction();
BroadcastItem item = new BroadcastItem();
for (int i = 0 ; i < 5 ; i++) {
entry = (SyndEntry) feed.getEntries().get(i);
item.setMessage(entry.getTitle());
item.setLinkUrl(entry.getLink());
session.save(item);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
// Rolling back the changes to make the data consistent in case of any failure in between multiple database write operations.
tx.rollback();
} finally{
if(session != null) {
session.close();
}
}
但是当我在for循环中移动tx = session.beginTransaction();
时,我得到了
不支持嵌套交易
答案 0 :(得分:4)
写作时
BroadcastItem item = new BroadcastItem();
for (int i = 0 ; i < 5 ; i++) {
entry = (SyndEntry) feed.getEntries().get(i);
item.setMessage(entry.getTitle());
item.setLinkUrl(entry.getLink());
session.save(item);
}
您第一次保存(创建)item
,而在循环的其他时间,您保存(更新)item
。
您只需要在循环中创建BroadcastItem
,如下所示:
for (int i = 0 ; i < 5 ; i++) {
entry = (SyndEntry) feed.getEntries().get(i);
BroadcastItem item = new BroadcastItem();
item.setMessage(entry.getTitle());
item.setLinkUrl(entry.getLink());
session.save(item);
}