Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Saving files to hard disk + data in database

 
roul ravashimka
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I've made an application that saves uploaded files to the hard disk and saves additional data about the file in a database.
This is mainly done by a Struts-controller: saving to hard disk and by a Business Delegate, Session Facaede, EJB's the addition data is saved in de database.
My question is: how can i be sure that both action are done?
It is possible that only the file is saved to hard disk and the additional data not stored in the database opr visa versa.
Someone who can help?
Thanks,

Roul
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wrap both action in a transaction. Any exceptions occur and the whole operation will rollback, rather than just part of it.
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And save to harddisk after inserting into the database, because you can't rollback the disk I/O as easily as you can rollback the JDBC stuff.
 
roul ravashimka
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,
thanks for your replies,
i've tried the container managed transaction for inserting two fields in my database, this seems to work: when one of the two already exists, none of the two are added and when none of them already exist, they are both added.
But now, when i try to add the data about the file in the database and write the file to my hard disk (in one transaction), it always writes the file?
Do i have to include some code to rollback the file-writing such as:
File f = new File("...");
f.delete();
or can the container do this in some way?
or mayby something else i look over?
Thanks in advance,
Roul
 
Lasse Koskela
author
Sheriff
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact is that java.io.* does not provide any kind of transactions. What you write to a file is not rolled back when your JTA transaction rolls back.
That's exactly why I said that you should first write to database and then, only if the database insert succeeded, write to disk.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic