Le blog de pingou - Tag - MySQLLe blog de pingou, ses actualités sur Fedora, ses RPMs, ses tests, son Linux... :-)
Pingou's weblog, his fedora's news, his RPMs, his tests, his Linux... :-)2022-02-17T10:46:15+01:00pingouurn:md5:66db5ce1ed1a80cb2f424695b4bb7780DotclearJava JPA and rollback on MySQLurn:md5:f54fd951cb3eee809840f76b77c2d9952012-06-18T18:40:00+01:002012-06-18T18:40:00+01:00Pierre-YvesBioinformatiqueAstucesFedora-planetjavaMySQLpersistance <p><img src="https://blog.pingoured.fr/public/source.png" alt="source.png" /></p>
<p>We (b8e5n and I) have been fighting for too long for this, so there it is dear lazy web.</p>
<p>Using the eclipse <a href="http://en.wikipedia.org/wiki/Java_Persistence_API">JPA (Java Persistence API)</a> to connect to a MySQL database you might experienced some troubles.</p>
<p>Using the following piece of code:</p>
<pre>
transaction = manager.getTransaction();
transaction.begin();
try {
// Add here your logic
transaction.commit();
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
}
</pre>
<p>We kept running into the fact that the rollback never happened. The commit was performed or at least started and if something was going wrong at the database level (like an already existing primary key), the data already commited to the database would remain in there.</p>
<p>So yay for the half-commited data :-s</p>
<p>It took us a while but we finally ended up finding the solution on a lost <a href="http://www.developerscrappad.com/547/java/java-ee/ejb3-x-jpa-when-to-use-rollback-and-setrollbackonly/">corner of the web</a>:</p>
<p><strong>** Please take special note for MySQL database users: do make sure that your tables are InnoDB tables instead of MyISAM. If not, rollback will not occur.</strong></p>
<p>Switching from MyISAM to InnoDB solved the problem for us, the transaction is either fully commited or not at all.</p>
<p>Hope this can help.</p>