Reputation: 913
Trying to use a for loop to save/commit data using hibernate 4.3.11.Final with SQLite Dialect com.enigmabridge:hibernate4-sqlite-dialect
When I run this code and check the Sqlite data, I see that it's only saved 1 item (seems like it only commits once) and that one item is the last (of the 5 items I've generated) that I see in the database.
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();
}
}
But when I move tx = session.beginTransaction();
inside the for loop, I get
nested transactions not supported
Upvotes: 1
Views: 3575
Reputation: 1047
When you write
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);
}
You save (create) your item
the first time, and for the other times of your loop, you save (update) your item
.
You just need to put your creation of your BroadcastItem
in the loop as follows:
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);
}
Upvotes: 6