{"id":48952,"date":"2017-08-04T11:00:42","date_gmt":"2017-08-04T08:00:42","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=48952"},"modified":"2019-03-05T13:02:43","modified_gmt":"2019-03-05T11:02:43","slug":"jdbc-nested-transactions-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/","title":{"rendered":"JDBC Nested Transactions Example"},"content":{"rendered":"<p>A <strong>nested transaction<\/strong> is used to provide a transactional guarantee for a subset of operations performed within the scope of a larger transaction. Doing this allows us to commit and abort the subset of operations independently of the larger transaction.<\/p>\n<p>This operation is theoretically possible, however, in JDBC 3.0 we can\u2019t achieve this as easily as the definition looks. In JDBC, programmers can achieve this effect using <strong>savepoints<\/strong>.<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;\n<\/p>\n<h2>1. Introduction<\/h2>\n<p>In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the <em>JDBC Savepoints<\/em>.<\/p>\n<h3>1.1 Why JDBC Transactions?<\/h3>\n<p>In the database systems, <strong>Transaction<\/strong> is a set of actions to be carried out as a single or an atomic action. Either all of the actions are carried out, or none of them.<\/p>\n<p>The classic example of when transactions are necessary is the example of <span style=\"text-decoration: underline;\">bank accounts<\/span>. Let\u2019s say you need to transfer $100 from one account to the other. You do so by subtracting $100 from the first account, and adding $100 to the second account. If this process fails after you have subtracted the $100 from the first bank account, the $100 are never added to the second bank account and hence the money is lost in the cyber space.<\/p>\n<p>To solve this problem, the subtraction and addition of the $100 are grouped into a <em>transaction<\/em>. If the subtraction succeeds, but the addition fails, you can roll-back the first subtraction. That way the database is left in the same state as before the subtraction was executed.<\/p>\n<h3>1.2 What are JDBC Transactions?<\/h3>\n<p>A <strong>transaction<\/strong> is a group of operation used to perform a single task; if all operations in the group are a success then the task is finished and the transaction is successfully completed. But if anyone operation in the group is failed, then the task is failed and the transaction is failed.<\/p>\n<p><figure id=\"attachment_48953\" aria-describedby=\"caption-attachment-48953\" style=\"width: 523px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architecture-guide-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48953\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architecture-guide-1.jpg\" alt=\"Fig. 1: Java Database Connectivity (JDBC) Transactions\" width=\"523\" height=\"273\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architecture-guide-1.jpg 523w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architecture-guide-1-300x157.jpg 300w\" sizes=\"(max-width: 523px) 100vw, 523px\" \/><\/a><figcaption id=\"caption-attachment-48953\" class=\"wp-caption-text\">Fig. 1: Java Database Connectivity (JDBC) Transactions<\/figcaption><\/figure><\/p>\n<p>Let\u2019s consider a movie ticket booking is a transaction. This task contains 4 operations:<\/p>\n<ol>\n<li>Choose the seats.<\/li>\n<li>Reserve the seats.<\/li>\n<li>Payment.<\/li>\n<li>Issue the movie tickets.<\/li>\n<\/ol>\n<p>If all the above 4 operations are done successfully then a transaction is <em>finished<\/em> successfully. But if any one operation is failed in the middle then all operations are canceled and the transaction is <em>failed<\/em>.<\/p>\n<h3>1.3 Properties of Transaction Management<\/h3>\n<p>Every JDBC Transaction follows some transaction properties and these are called as <strong>ACID<\/strong> properties. ACID stands for <em>Atomicity<\/em>, <em>Consistency<\/em>, <em>Isolation<\/em>, and <em>Durability<\/em>.<\/p>\n<p><figure id=\"attachment_48973\" aria-describedby=\"caption-attachment-48973\" style=\"width: 754px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architectur-guide-2.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48973\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architectur-guide-2.jpg\" alt=\"Fig. 2: JDBC Transaction Management Properties\" width=\"754\" height=\"253\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architectur-guide-2.jpg 754w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-architectur-guide-2-300x101.jpg 300w\" sizes=\"(max-width: 754px) 100vw, 754px\" \/><\/a><figcaption id=\"caption-attachment-48973\" class=\"wp-caption-text\">Fig. 2: JDBC Transaction Management Properties<\/figcaption><\/figure><\/p>\n<ul>\n<li><strong>Atomicity<\/strong>: Atomicity of a transaction is defined as either all the operations can be done or all the operation can be undone, but some operations are done and some operation is undone should not occur.<\/li>\n<li><strong>Consistency<\/strong>: Consistency means, after a transaction is completed successfully, the data in the datastore should be a reliable data and this reliable data is also called as consistent data.<\/li>\n<li><strong>Isolation<\/strong>: Isolation means if two transactions are going on the same data than one transaction will not disturb the another transaction.<\/li>\n<li><strong>Durability<\/strong>: Durability means after a transaction is completed the data in the datastore will be permanent until another transaction is going to be performed on that data.<\/li>\n<\/ul>\n<h3>1.4 Types of Transaction Management<\/h3>\n<ul>\n<li><strong>Local Transaction<\/strong>: A local transaction means, all operation in a transaction is executed against one database. For e.g.: If transfer money from first account to second account belongs to the same bank then the transaction is a local transaction.<\/li>\n<li><strong>Distributed or Global Transaction<\/strong>: A global transaction means, all operations in a transaction are executed against multiple databases. For e.g.: If transfer money from first account to second account belongs to different banks then the transaction is a global transaction.<\/li>\n<\/ul>\n<div class=\"tip\"><strong>Tip<\/strong><br \/>\nJDBC technology only performs the Local Transactions. For Global Transaction in Java, we need either <code>EJB<\/code> or <code>Spring<\/code> framework.<\/div>\n<h3>1.5 Advantage of Transaction Management<\/h3>\n<ul>\n<li><strong>Fast Performance<\/strong>: JDBC Transactions makes the performance fast because the database is hit only at the time of commit.<\/li>\n<\/ul>\n<h3>1.6 Things Required for JDBC Transactions<\/h3>\n<p>To perform the transaction management in JDBC, we need to follow the below steps:<\/p>\n<ol>\n<li>Disable auto commit mode of JDBC.<\/li>\n<li>Put all operations of a transaction in <code>try<\/code> block.<\/li>\n<li>If all operations are done successfully then commit in the <code>try<\/code> block, otherwise rollback in a <code>catch<\/code> block.<\/li>\n<\/ol>\n<p>By default, in JDBC auto-commit mode is <em>enabled<\/em> but developers need to <em>disable<\/em> it. To disable, call the <code>setAutoCommit()<\/code> method of the <code>connection<\/code> interface.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Method Syntax<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false;\">connObj.setAutoCommit(false);\n<\/pre>\n<h3>1.7 Download and Install MySQL<\/h3>\n<p>In this example, we are using the MySQL database to perform the JDBC Transaction Management. You can watch <a href=\"https:\/\/www.youtube.com\/watch?v=z1t9m7K6cpI\" target=\"_blank\" rel=\"noopener noreferrer\">this<\/a> video in order to download and install the MySQL database on your Windows operating system.<\/p>\n<p>Now, open up the Eclipse IDE and let\u2019s start building the application!<\/p>\n<h2>2. JDBC Nested Transactions Example<\/h2>\n<h3>2.1 Tools Used<\/h3>\n<p>We are using Eclipse Kepler SR2, JDK 7, MySQL Database and Maven. Having said that, we have tested the code against JDK 1.8 and it works well.<\/p>\n<h3>2.2 Project Structure<\/h3>\n<p>Firstly, let\u2019s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!<\/p>\n<p><figure id=\"attachment_48955\" aria-describedby=\"caption-attachment-48955\" style=\"width: 294px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-structure-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48955\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-structure-1.jpg\" alt=\"Fig. 3: JDBC Nested Transactions Application Project Structure\" width=\"294\" height=\"360\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-structure-1.jpg 294w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-structure-1-245x300.jpg 245w\" sizes=\"(max-width: 294px) 100vw, 294px\" \/><\/a><figcaption id=\"caption-attachment-48955\" class=\"wp-caption-text\">Fig. 3: JDBC Nested Transactions Application Project Structure<\/figcaption><\/figure><\/p>\n<h3>2.3 Project Creation<\/h3>\n<p>This section will demonstrate on how to create a Java Maven project with Eclipse. In Eclipse IDE, go to <code>File -&gt; New -&gt; Maven Project<\/code>.<\/p>\n<p><figure id=\"attachment_48956\" aria-describedby=\"caption-attachment-48956\" style=\"width: 652px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48956\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-1.jpg\" alt=\"Fig. 4: Create Maven Project\" width=\"652\" height=\"712\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-1.jpg 652w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-1-275x300.jpg 275w\" sizes=\"(max-width: 652px) 100vw, 652px\" \/><\/a><figcaption id=\"caption-attachment-48956\" class=\"wp-caption-text\">Fig. 4: Create Maven Project<\/figcaption><\/figure><\/p>\n<p>In the New Maven Project window, it will ask you to select a project location. By default, &#8216;<em>Use default workspace location<\/em>&#8216; will be selected. Select the &#8216;<em>Create a simple project (skip archetype selection)<\/em>&#8216; checkbox and just click on next button to proceed.<\/p>\n<p><figure id=\"attachment_48957\" aria-describedby=\"caption-attachment-48957\" style=\"width: 804px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-2.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48957\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-2.jpg\" alt=\"Fig. 5: Project Details\" width=\"804\" height=\"541\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-2.jpg 804w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-2-300x202.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-2-768x517.jpg 768w\" sizes=\"(max-width: 804px) 100vw, 804px\" \/><\/a><figcaption id=\"caption-attachment-48957\" class=\"wp-caption-text\">Fig. 5: Project Details<\/figcaption><\/figure><div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>It will ask you to &#8216;Enter a group and artifact id for the project.&#8217; We will input the details as shown in the below image. The version number will be by default <code>0.0.1-SNAPSHOT<\/code>.<\/p>\n<p><figure id=\"attachment_48958\" aria-describedby=\"caption-attachment-48958\" style=\"width: 600px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-3.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48958\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-3.jpg\" alt=\"Fig. 6: Archetype Parameters\" width=\"600\" height=\"546\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-3.jpg 600w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-3-300x273.jpg 300w\" sizes=\"(max-width: 600px) 100vw, 600px\" \/><\/a><figcaption id=\"caption-attachment-48958\" class=\"wp-caption-text\">Fig. 6: Archetype Parameters<\/figcaption><\/figure><\/p>\n<p>Click on Finish and the creation of a maven project will be completed. If you observe, it has downloaded the maven dependencies and a <code>pom.xml<\/code> file will be created. It will have the following code:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>pom.xml<\/em><\/span><\/p>\n<pre class=\"brush:xml; wrap-lines:false;\">&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\"&gt;\n\t&lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n\t&lt;groupId&gt;JdbcTransactions&lt;\/groupId&gt;\n\t&lt;artifactId&gt;JdbcTransactions&lt;\/artifactId&gt;\n\t&lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n&lt;\/project&gt;\n<\/pre>\n<p>We can start adding the dependencies that developers want like MySQL, Log4J etc. Let\u2019s start building the application!<\/p>\n<h2>3. Application Building<\/h2>\n<p>Below are the steps involved in developing this application.<\/p>\n<h3>3.1 Database &amp; Table Creation<\/h3>\n<p>This tutorial uses a database called <code>tutorialDb<\/code>. The database is not included when you create the project in eclipse so you need to first create the database to follow this tutorial.<\/p>\n<ul>\n<li>Create a new database <code>tutorialDb<\/code> as:<\/li>\n<\/ul>\n<pre class=\"brush:sql;\">CREATE DATABASE tutorialDb;\n<\/pre>\n<ul>\n<li>Use the created database <code>tutorialDb<\/code> to create table as:<\/li>\n<\/ul>\n<pre class=\"brush:sql;\">USE tutorialDb;\n<\/pre>\n<ul>\n<li>Create the table <code>user_table<\/code> as shown below:<\/li>\n<\/ul>\n<pre class=\"brush:sql; wrap-lines:false;\">CREATE TABLE user_table (user_id int(11), user_name varchar(15), created_by varchar(100), created_date DATE, PRIMARY KEY (user_id));\n<\/pre>\n<p>If everything goes well, the table will be shown as below in the MySQL workbench:<\/p>\n<p><figure id=\"attachment_48959\" aria-describedby=\"caption-attachment-48959\" style=\"width: 849px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-database-guide-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48959\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-database-guide-1.jpg\" alt=\"Fig. 7: Database &amp; Table Creation\" width=\"849\" height=\"245\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-database-guide-1.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-database-guide-1-300x87.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-database-guide-1-768x222.jpg 768w\" sizes=\"(max-width: 849px) 100vw, 849px\" \/><\/a><figcaption id=\"caption-attachment-48959\" class=\"wp-caption-text\">Fig. 7: Database &amp; Table Creation<\/figcaption><\/figure><\/p>\n<h3>3.2 Maven Dependencies<\/h3>\n<p>In this example, we are using the latest MySQL version (i.e. <code>mysql-connector-java-5.1.21<\/code>) and Log4J dependencies. The <strong>updated<\/strong> file will have the following code:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>pom.xml<\/em><\/span><\/p>\n<pre class=\"brush:xml; wrap-lines:false;\">&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\"&gt;\n\t&lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n\t&lt;groupId&gt;JdbcTransactions&lt;\/groupId&gt;\n\t&lt;artifactId&gt;JdbcTransactions&lt;\/artifactId&gt;\n\t&lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n\t&lt;packaging&gt;jar&lt;\/packaging&gt;\n\t&lt;dependencies&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;mysql&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;mysql-connector-java&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;5.1.21&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;log4j&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;log4j&lt;\/artifactId&gt;\n\t\t\t&lt;version&gt;1.2.16&lt;\/version&gt;\n\t\t&lt;\/dependency&gt;\n\t&lt;\/dependencies&gt;\n\t&lt;build&gt;\n\t\t&lt;finalName&gt;${project.artifactId}&lt;\/finalName&gt;\n\t&lt;\/build&gt;\n&lt;\/project&gt;\n<\/pre>\n<h3>3.3 Java Class Creation<\/h3>\n<p>Let\u2019s create the required Java files. Right click on <code>src\/main\/java<\/code> folder, <code>New -&gt; Package<\/code>.<\/p>\n<p><figure id=\"attachment_48960\" aria-describedby=\"caption-attachment-48960\" style=\"width: 671px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-4.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48960\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-4.jpg\" alt=\"Fig. 8: Java Package Creation\" width=\"671\" height=\"661\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-4.jpg 671w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-4-300x296.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-4-70x70.jpg 70w\" sizes=\"(max-width: 671px) 100vw, 671px\" \/><\/a><figcaption id=\"caption-attachment-48960\" class=\"wp-caption-text\">Fig. 8: Java Package Creation<\/figcaption><\/figure><\/p>\n<p>A new pop window will open where we will enter the package name as: <code>com.jcg.jdbc.transactions.example<\/code>.<\/p>\n<p><figure id=\"attachment_48961\" aria-describedby=\"caption-attachment-48961\" style=\"width: 520px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-5.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48961\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-5.jpg\" alt=\"Fig. 9: Java Package Name (com.jcg.jdbc.transactions.example)\" width=\"520\" height=\"426\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-5.jpg 520w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-5-300x246.jpg 300w\" sizes=\"(max-width: 520px) 100vw, 520px\" \/><\/a><figcaption id=\"caption-attachment-48961\" class=\"wp-caption-text\">Fig. 9: Java Package Name (com.jcg.jdbc.transactions.example)<\/figcaption><\/figure><\/p>\n<p>Once the package is created, we will need to create the implementation classes. Right click on the newly created package, <code>New -&gt; Class<\/code>.<\/p>\n<p><figure id=\"attachment_48962\" aria-describedby=\"caption-attachment-48962\" style=\"width: 762px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-6.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48962\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-6.jpg\" alt=\"Fig. 10: Java Class Creation\" width=\"762\" height=\"662\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-6.jpg 762w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-6-300x261.jpg 300w\" sizes=\"(max-width: 762px) 100vw, 762px\" \/><\/a><figcaption id=\"caption-attachment-48962\" class=\"wp-caption-text\">Fig. 10: Java Class Creation<\/figcaption><\/figure><\/p>\n<p>A new pop window will open and enter the file name as: <code>JDBCTransactionsDemo<\/code>. The implementation class will be created inside the package: <code>com.jcg.jdbc.transactions.example<\/code>.<\/p>\n<p><figure id=\"attachment_48963\" aria-describedby=\"caption-attachment-48963\" style=\"width: 536px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-7.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48963\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-7.jpg\" alt=\"Fig. 11: Java Class (JDBCTransactionsDemo.java)\" width=\"536\" height=\"632\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-7.jpg 536w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-7-254x300.jpg 254w\" sizes=\"(max-width: 536px) 100vw, 536px\" \/><\/a><figcaption id=\"caption-attachment-48963\" class=\"wp-caption-text\">Fig. 11: Java Class (JDBCTransactionsDemo.java)<\/figcaption><\/figure><\/p>\n<p>Repeat the step (i.e. Fig. 10) and enter the filename as <code>JDBCTransactionSavePointDemo<\/code>. The Savepoint implementation class will be created inside the package: <code>com.jcg.jdbc.transactions.example<\/code>.<\/p>\n<p><figure id=\"attachment_48964\" aria-describedby=\"caption-attachment-48964\" style=\"width: 536px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-8.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48964\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-8.jpg\" alt=\"Fig. 12: Java Class (JDBCTransactionSavePointDemo.java)\" width=\"536\" height=\"630\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-8.jpg 536w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-guide-8-255x300.jpg 255w\" sizes=\"(max-width: 536px) 100vw, 536px\" \/><\/a><figcaption id=\"caption-attachment-48964\" class=\"wp-caption-text\">Fig. 12: Java Class (JDBCTransactionSavePointDemo.java)<\/figcaption><\/figure><\/p>\n<h4>3.3.1 Implementation of Main Class<\/h4>\n<p>In JDBC, <code>Connection<\/code> interface provides different methods to carefully manage the JDBC Transactions,<\/p>\n<table>\n<tbody>\n<tr>\n<th><strong>Method<\/strong><\/th>\n<th><strong>Description<\/strong><\/th>\n<\/tr>\n<tr>\n<td><code>void setAutoCommit(boolean status)<\/code><\/td>\n<td>It is set by default to <em>true<\/em> i.e. each transaction is auto committed to the database. Developers need to set it to <em>false<\/em> so that they themselves can commit or rollback the data based on the conditions.<\/td>\n<\/tr>\n<tr>\n<td><code>void commit()<\/code><\/td>\n<td>Commits the transaction (i.e. data) to the database.<\/td>\n<\/tr>\n<tr>\n<td><code>void rollback()<\/code><\/td>\n<td>Cancels the transaction from the database. Usually, developers add this statement in <code>catch<\/code> block.<\/td>\n<\/tr>\n<tr>\n<td><code>setSavepoint()<\/code><\/td>\n<td>Allows developers to assign or create a logical group and by using <code>rollback(String)<\/code> method we can roll-back all the statements after the given savepoint has been set.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<p>Let&#8217;s see the simple example of transaction management using <code>PreparedStatement<\/code>. Add the following code to it:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>JDBCTransactionsDemo.java<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false;\">package com.jcg.jdbc.transactions.example;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\nimport org.apache.log4j.Logger;\n\npublic class JDBCTransactionsDemo {\n\n\t\/\/ JDBC Driver Name &amp; Database URL\n\tprivate final static String JDBC_DRIVER = \"com.mysql.jdbc.Driver\";  \n\tprivate final static String JDBC_DB_URL = \"jdbc:mysql:\/\/localhost:3306\/tutorialDb\";\n\n\t\/\/ JDBC Database Credentials\n\tprivate final static String JDBC_USER = \"root\";\n\tprivate final static String JDBC_PASS = \"\";\n\n\tprivate static Connection connObj;\n\tpublic final static Logger logger = Logger.getLogger(JDBCTransactionsDemo.class);\n\n\tpublic static void connectDb() {\n\t\ttry {\n\t\t\tClass.forName(JDBC_DRIVER);\n\t\t\tconnObj = DriverManager.getConnection(JDBC_DB_URL, JDBC_USER, JDBC_PASS);\n\t\t\tlogger.info(\"\\n=======DATABASE CONNECTION OPEN=======\\n\");\n\t\t} catch(Exception sqlException) {\n\t\t\tsqlException.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static void disconnectDb() {\n\t\ttry {\n\t\t\tconnObj.close();\n\t\t\tlogger.info(\"\\n=======DATABASE CONNECTION CLOSED=======\\n\");\n\t\t} catch (Exception sqlException) {\n\t\t\tsqlException.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static void showTableRecords(String table_name) throws SQLException {\n\t\tResultSet rsObj = null;\n\t\tStatement stmtObj = connObj.createStatement();\t\n\t\trsObj = stmtObj.executeQuery(\"select user_id, user_name, created_date from \" + table_name + \";\");\n\t\tif(!rsObj.next()) {\n\t\t\tlogger.info(\"No Records In The Table\\n\");\n\t\t} else {\n\t\t\tlogger.info(\"Id: \"+ rsObj.getInt(\"user_id\") + \", Name: \" + rsObj.getString(\"user_name\") + \", Joining Date: \" + rsObj.getInt(\"created_date\") + \"\\n\");\n\t\t}\n\t}\n\n\tpublic static void saveUserDetails(int userId, String userName, String sysName) {\n\n\t\tPreparedStatement insertStatement = null, \n\t\t\t\tupdateStatement = null;\n\n\t\ttry {\n\t\t\tconnObj.setAutoCommit(false);\n\n\t\t\tlogger.info(\"\\n=======Inserting Data In The Table=======\\n\");\n\t\t\tString insertTableSQL = \"insert into user_table (user_id, user_name, created_by, created_date) VALUES (?, ?, ?, ?);\";\n\n\t\t\tinsertStatement = connObj.prepareStatement(insertTableSQL);\n\t\t\tinsertStatement.setInt(1, userId);\n\t\t\tinsertStatement.setString(2, userName);\n\t\t\tinsertStatement.setString(3, sysName);\n\t\t\tinsertStatement.setTimestamp(4, new java.sql.Timestamp(new java.util.Date().getTime()));\n\t\t\tinsertStatement.executeUpdate();\t\t\/\/ Record Is Not Committed In Database At This Moment \n\n\t\t\tlogger.info(\"\\n=======Updating Value In The Table=======\\n\");\n\t\t\tString updateTableSQL = \"update user_table set user_name =? where user_id = ?\";\n\n\t\t\tupdateStatement = connObj.prepareStatement(updateTableSQL);\n\n\t\t\t\/\/ Line No. 79 - This line Will Result In An Exception &amp; The Data Will Rollback Including The 'Insert' Statement.\n\t\t\tupdateStatement.setString(1, \"A Very Very Long String Resulting In A Database Error\");\n\n\t\t\t\/\/ updateStatement.setString(1, \"Lucifer Star\");\n\t\t\tupdateStatement.setInt(2, userId);\n\t\t\tupdateStatement.executeUpdate();\n\n\t\t\tconnObj.commit();\n\t\t\tshowTableRecords(\"user_table\");\n\t\t} catch (Exception sqlException) {\n\t\t\ttry {\n\t\t\t\tconnObj.rollback();\n\t\t\t\tlogger.info(\"\\n=======!Db Exception! Rolling Back Data=======\\n\");\n\t\t\t\tshowTableRecords(\"user_table\");\n\t\t\t} catch (SQLException sqlEx) {\n\t\t\t\tsqlEx.printStackTrace();\n\t\t\t}\t\t\t\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (insertStatement != null ) {\n\t\t\t\t\tinsertStatement.close();\n\t\t\t\t}\n\t\t\t\tif (updateStatement != null ) {\n\t\t\t\t\tupdateStatement.close();\n\t\t\t\t}\n\t\t\t\tconnObj.setAutoCommit(true);\n\t\t\t} catch (Exception sqlException) {\n\t\t\t\tsqlException.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tconnectDb();\n\t\tsaveUserDetails(101, \"Harry Potter\", \"sys_admin\");\n\t\tdisconnectDb();\n\t}\n}\n<\/pre>\n<p>We will try to execute the transaction in the above example and the below result will be displayed.[ulp id=&#8217;TD36VgQCKfhTAygK&#8217;]<\/p>\n<p><figure id=\"attachment_48965\" aria-describedby=\"caption-attachment-48965\" style=\"width: 849px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48965\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-1.jpg\" alt=\"Fig. 13: Output for JDBCTransactionsDemo.java\" width=\"849\" height=\"169\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-1.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-1-300x60.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-1-768x153.jpg 768w\" sizes=\"(max-width: 849px) 100vw, 849px\" \/><\/a><figcaption id=\"caption-attachment-48965\" class=\"wp-caption-text\">Fig. 13: Output for JDBCTransactionsDemo.java<\/figcaption><\/figure><\/p>\n<p>Here we should note that, <code>UPDATE<\/code> <span style=\"text-decoration: underline;\">operation does not run correctly<\/span>, hence the <code>INSERT<\/code> entry isn\u2019t made and the database remains unchanged.<\/p>\n<p><figure id=\"attachment_48966\" aria-describedby=\"caption-attachment-48966\" style=\"width: 849px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-database-output-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48966\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-database-output-1.jpg\" alt=\"Fig. 14: Output from MySQL Workbench\" width=\"849\" height=\"53\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-database-output-1.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-database-output-1-300x19.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-database-output-1-768x48.jpg 768w\" sizes=\"(max-width: 849px) 100vw, 849px\" \/><\/a><figcaption id=\"caption-attachment-48966\" class=\"wp-caption-text\">Fig. 14: Output from MySQL Workbench<\/figcaption><\/figure><\/p>\n<h4>3.3.2 Implementation of Savepoints Main Class<\/h4>\n<p>The JDBC API provides the <code>connObj.setSavepoint()<\/code> method that marks a point to which the transaction can be rolled back. The <code>rollback()<\/code> method is an overloaded method to take a savepoint as its argument: <code>connObj.rollback(savepointObj)<\/code>.<\/p>\n<p>The following code will help you understand how the savepoints are used in a JDBC Transaction:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>JDBCTransactionSavePointDemo.java<\/em><\/span><\/p>\n<pre class=\"brush:java; wrap-lines:false;\"> \npackage com.jcg.jdbc.transactions.example;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Savepoint;\nimport java.sql.Statement;\n\nimport org.apache.log4j.Logger;\n\npublic class JDBCTransactionSavePointDemo {\n\n\t\/\/ JDBC Driver Name &amp; Database URL\n\tprivate final static String JDBC_DRIVER = \"com.mysql.jdbc.Driver\";  \n\tprivate final static String JDBC_DB_URL = \"jdbc:mysql:\/\/localhost:3306\/tutorialDb\";\n\n\t\/\/ JDBC Database Credentials\n\tprivate final static String JDBC_USER = \"root\";\n\tprivate final static String JDBC_PASS = \"\";\n\n\tprivate static Connection connObj;\n\tpublic final static Logger logger = Logger.getLogger(JDBCTransactionsDemo.class);\n\n\tpublic static void connectDb() {\n\t\ttry {\n\t\t\tClass.forName(JDBC_DRIVER);\n\t\t\tconnObj = DriverManager.getConnection(JDBC_DB_URL, JDBC_USER, JDBC_PASS);\n\t\t\tlogger.info(\"\\n=======DATABASE CONNECTION OPEN=======\\n\");\n\t\t} catch(Exception sqlException) {\n\t\t\tsqlException.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static void disconnectDb() {\n\t\ttry {\n\t\t\tconnObj.close();\n\t\t\tlogger.info(\"\\n=======DATABASE CONNECTION CLOSED=======\\n\");\n\t\t} catch (Exception sqlException) {\n\t\t\tsqlException.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static void showTableRecords(String table_name) throws SQLException {\n\t\tResultSet rsObj = null;\n\t\tStatement stmtObj = connObj.createStatement();\t\n\t\trsObj = stmtObj.executeQuery(\"select user_id, user_name, created_date from \" + table_name + \";\");\n\t\tif(!rsObj.next()) {\n\t\t\tlogger.info(\"No Records In The Table\\n\");\n\t\t} else {\n\t\t\tlogger.info(\"Id: \"+ rsObj.getInt(\"user_id\") + \", Name: \" + rsObj.getString(\"user_name\") + \", Joining Date: \" + rsObj.getInt(\"created_date\") + \"\\n\");\n\t\t}\n\t}\n\n\tpublic static void saveUserDetails(int userId, String userName, String sysName) {\n\n\t\tPreparedStatement insertStatement = null, \n\t\t\t\tupdateStatement = null;\n\n\t\tSavepoint saveObj =null;\n\n\t\ttry {\n\t\t\tconnObj.setAutoCommit(false);\n\n\t\t\tlogger.info(\"\\n=======Inserting Data In The Table=======\\n\");\n\t\t\tString insertTableSQL = \"insert into user_table (user_id, user_name, created_by, created_date) VALUES (?, ?, ?, ?);\";\n\n\t\t\tinsertStatement = connObj.prepareStatement(insertTableSQL);\n\t\t\tinsertStatement.setInt(1, userId);\n\t\t\tinsertStatement.setString(2, userName);\n\t\t\tinsertStatement.setString(3, sysName);\n\t\t\tinsertStatement.setTimestamp(4, new java.sql.Timestamp(new java.util.Date().getTime()));\n\t\t\tinsertStatement.executeUpdate();\t\t\/\/ Record Is Not Committed In Database At This Moment\n\n\t\t\tsaveObj = connObj.setSavepoint();\t\/\/ Savepoint Will Allow To RollBack Only Till This Checkpoint Incase An Exception Occurs.\n\n\t\t\tlogger.info(\"\\n=======Updating Value In The Table=======\\n\");\n\t\t\tString updateTableSQL = \"update user_table set user_name =? where user_id = ?\";\n\n\t\t\tupdateStatement = connObj.prepareStatement(updateTableSQL);\n\n\t\t\t\/\/ Line No. 84 - This line Will Result In An Exception &amp; The Data Will Rolled-Back\n\t\t\tupdateStatement.setString(1, \"A Very Very Long String Resulting In A Database Error\");\n\n\t\t\t\/\/ updateStatement.setString(1, \"Lucifer Star\");\n\t\t\tupdateStatement.setInt(2, userId);\n\t\t\tupdateStatement.executeUpdate();\n\n\t\t\tconnObj.commit();\n\t\t\tshowTableRecords(\"user_table\");\n\t\t} catch (Exception sqlException) {\n\t\t\ttry {\n\t\t\t\tconnObj.rollback(saveObj);\t\t\t\t\t\/\/ Here, The Rollback Command Will Execute But The 'Insert' Will Still Be Committed To The Database As We Have Introduced A Savepoint at Line No. 76\n\t\t\t\tlogger.info(\"\\n=======!Db Exception! Rolling Back The Update Data But Not Insert=======\\n\");\n\t\t\t\tshowTableRecords(\"user_table\");\n\t\t\t} catch (SQLException sqlEx) {\n\t\t\t\tsqlEx.printStackTrace();\n\t\t\t}\t\t\t\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (insertStatement != null ) {\n\t\t\t\t\tinsertStatement.close();\n\t\t\t\t}\n\t\t\t\tif (updateStatement != null ) {\n\t\t\t\t\tupdateStatement.close();\n\t\t\t\t}\n\t\t\t\tconnObj.setAutoCommit(true);\n\t\t\t} catch (Exception sqlException) {\n\t\t\t\tsqlException.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tconnectDb();\n\t\tsaveUserDetails(101, \"Harry Potter\", \"sys_admin\");\n\t\tdisconnectDb();\n\t}\n}\n<\/pre>\n<p><strong>Do Note<\/strong>:<\/p>\n<ul>\n<li>The JDBC API provides the <code>connObj.releaseSavepoint(savepointObj)<\/code> method that removes the specified savepoint from the current transaction. A savepoint that has been released become invalid and cannot be rolled back to. Any attempt to roll back the transaction to a released savepoint causes a <code>SQLException<\/code>.<\/li>\n<li>A savepoint is automatically released and becomes invalid when the transaction is committed or when the entire transaction is rolled back.<\/li>\n<\/ul>\n<h2>4. Run the Application<\/h2>\n<p>To run the application, Right click on the <code>JDBCTransactionSavePointDemo<\/code> class, <code>Run As -&gt; Java Application<\/code>.<\/p>\n<p><figure id=\"attachment_48968\" aria-describedby=\"caption-attachment-48968\" style=\"width: 849px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-deploy-1.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48968\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-deploy-1.jpg\" alt=\"Fig. 15: Run Application\" width=\"849\" height=\"669\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-deploy-1.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-deploy-1-300x236.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-deploy-1-768x605.jpg 768w\" sizes=\"(max-width: 849px) 100vw, 849px\" \/><\/a><figcaption id=\"caption-attachment-48968\" class=\"wp-caption-text\">Fig. 15: Run Application<\/figcaption><\/figure><\/p>\n<h2>5. Project Demo<\/h2>\n<p>The code shows the following status as output:<\/p>\n<p><figure id=\"attachment_48969\" aria-describedby=\"caption-attachment-48969\" style=\"width: 849px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-2.jpg\"><img decoding=\"async\" class=\"size-full wp-image-48969\" src=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-2.jpg\" alt=\"Fig. 16: Application Output\" width=\"849\" height=\"171\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-2.jpg 849w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-2-300x60.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/jdbc-transaction-example-project-demo-2-768x155.jpg 768w\" sizes=\"(max-width: 849px) 100vw, 849px\" \/><\/a><figcaption id=\"caption-attachment-48969\" class=\"wp-caption-text\">Fig. 16: Application Output<\/figcaption><\/figure><\/p>\n<p>That\u2019s all for this post. Happy Learning!!<\/p>\n<h2>6. Conclusion<\/h2>\n<p>Here, in this example, we tried to understand how to manage the JDBC Operations through transactions and how to make check points by means of <code>Savepoint<\/code> class.<\/p>\n<h2>7. Download the Eclipse Project<\/h2>\n<p>This was an example of JBDC Transactions Using Savepoints.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/08\/Jdbc-Transactions.zip\" target=\"_blank\" rel=\"noopener noreferrer\"><strong>Jdbc Transactions<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>A nested transaction is used to provide a transactional guarantee for a subset of operations performed within the scope of a larger transaction. Doing this allows us to commit and abort the subset of operations independently of the larger transaction. This operation is theoretically possible, however, in JDBC 3.0 we can\u2019t achieve this as easily &hellip;<\/p>\n","protected":false},"author":119,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53],"tags":[189,216,647,247],"class_list":["post-48952","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-sql","tag-core-java-2","tag-jdbc-2","tag-mysql","tag-transactions-2"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>JDBC Nested Transactions Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the JDBC Savepoints in a Java application.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JDBC Nested Transactions Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the JDBC Savepoints in a Java application.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2017-08-04T08:00:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-03-05T11:02:43+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Yatin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Yatin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\"},\"author\":{\"name\":\"Yatin\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13\"},\"headline\":\"JDBC Nested Transactions Example\",\"datePublished\":\"2017-08-04T08:00:42+00:00\",\"dateModified\":\"2019-03-05T11:02:43+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\"},\"wordCount\":1717,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"keywords\":[\"core java\",\"jdbc\",\"mysql\",\"transactions\"],\"articleSection\":[\"sql\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\",\"name\":\"JDBC Nested Transactions Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2017-08-04T08:00:42+00:00\",\"dateModified\":\"2019-03-05T11:02:43+00:00\",\"description\":\"In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the JDBC Savepoints in a Java application.\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"sql\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/sql\/\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"JDBC Nested Transactions Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13\",\"name\":\"Yatin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg\",\"caption\":\"Yatin\"},\"description\":\"An experience full-stack engineer well versed with Core Java, Spring\/Springboot, MVC, Security, AOP, Frontend (Angular &amp; React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).\",\"sameAs\":[\"https:\/\/www.javacodegeeks.com\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/yatin-batra\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JDBC Nested Transactions Example - Java Code Geeks","description":"In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the JDBC Savepoints in a Java application.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/","og_locale":"en_US","og_type":"article","og_title":"JDBC Nested Transactions Example - Java Code Geeks","og_description":"In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the JDBC Savepoints in a Java application.","og_url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2017-08-04T08:00:42+00:00","article_modified_time":"2019-03-05T11:02:43+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"Yatin","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Yatin","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/"},"author":{"name":"Yatin","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13"},"headline":"JDBC Nested Transactions Example","datePublished":"2017-08-04T08:00:42+00:00","dateModified":"2019-03-05T11:02:43+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/"},"wordCount":1717,"commentCount":1,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","keywords":["core java","jdbc","mysql","transactions"],"articleSection":["sql"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/","url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/","name":"JDBC Nested Transactions Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2017-08-04T08:00:42+00:00","dateModified":"2019-03-05T11:02:43+00:00","description":"In this JDBC Nested Transactions example, we will see how to achieve this phenomenon by using the JDBC Savepoints in a Java application.","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/sql\/jdbc-nested-transactions-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"sql","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/sql\/"},{"@type":"ListItem","position":5,"name":"JDBC Nested Transactions Example"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/9874407a37b028e8be3276e2b5960d13","name":"Yatin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2023\/09\/cropped-Yatin-Batra_avatar_1515758148-96x96.jpg","caption":"Yatin"},"description":"An experience full-stack engineer well versed with Core Java, Spring\/Springboot, MVC, Security, AOP, Frontend (Angular &amp; React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).","sameAs":["https:\/\/www.javacodegeeks.com"],"url":"https:\/\/examples.javacodegeeks.com\/author\/yatin-batra\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/48952","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/119"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=48952"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/48952\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=48952"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=48952"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=48952"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}