PostgreSQL Tutorial

  • Home
  • Administration
  • Views
  • Triggers
  • Stored Procedures
  • Interfaces
    • PostgreSQL PHP
    • PostgreSQL Python
    • PostgreSQL JDBC
Home / PostgreSQL JDBC / The Beginner’s Guide To PostgreSQL JDBC Transaction

The Beginner’s Guide To PostgreSQL JDBC Transaction

Summary: in this tutorial, you will learn about the JDBC PostgreSQL transaction using JDBC transaction API.

In some cases, you do not want one SQL statement to take effect unless another one completes. For example, when you want to insert a new actor, you also want to assign the film that actor participates.

To make sure that both actions take effect nor neither actions occur, you use a transaction.

By definition, a transaction is a set of statements executed as a single unit. In other words, either all statements executed successfully, or none of them executed.

Disable auto-commit mode

When you establish a connection to the PostgreSQL database, it is in auto-commit mode. It means that each SQL statement is treated as a transaction and is automatically committed.

If you want to encapsulate one or more statements in a transaction, you must disable the auto-commit mode. To do this, you call the setAutoCommit() method of the Connection object as follows:

1
conn.setAutoCommit(false);

It is a best practice to disable the auto-commit mode only for the transaction mode. It allows you to avoid holding database locks for multiple statements.

Commit a transaction

To commit a transaction, you call the commit method of the Connection object as follows:

1
conn.commit();

When you call the commit() method, all the previous statements are committed together as a single unit.

Rollback a transaction

In case the result of one statement is not what you expected, you can use the rollback() method of the Connection object to aborting the current transaction and restore values to the original values.

1
conn.rollback();

PostgreSQL JDBC transaction example

Let’s take an example of using JDBC API to perform a PostgreSQL transaction.

We will insert a new actor into the actor table and assign the actor a film specified by a film id.

First, create a class that represents an actor as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.postgresqltutorial;
 
/**
*
* @author postgresqltutorial.com
*/
public class Actor {
 
    /**
     * actor's first name
     */
    private String firstName;
    /**
     * actor's last name
     */
    private String lastName;
 
    /**
     * initialize an actor with the first name and last name
     *
     * @param firstName
     * @param lastName
     */
    public Actor(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
 
    }
 
    /**
     * initialize an actor
     */
    public Actor() {
    }
 
    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }
 
    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }
 
    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Then, create an App class for the demonstration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/**
* need to fix the db ALTER TABLE film_actor ALTER COLUMN actor_id TYPE INT;
* ALTER TABLE film_actor ALTER COLUMN film_id TYPE INT;
*/
package com.postgresqltutorial;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
/**
*
* @author postgresqltutorial.com
*/
public class App {
 
    private final String url = "jdbc:postgresql://localhost/dvdrental";
    private final String user = "postgres";
    private final String password = "postgres";
 
    /**
     * Connect to the PostgreSQL database
     *
     * @return a Connection object
     * @throws java.sql.SQLException
     */
    public Connection connect() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
 
    /**
     * Close a AutoCloseable object
     *
     * @param closable
     */
    private App close(AutoCloseable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return this;
    }
 
    /**
     * insert an actor and assign him to a specific film
     *
     * @param actor
     * @param filmId
     */
    public void addActorAndAssignFilm(Actor actor, int filmId) {
 
        Connection conn = null;
        PreparedStatement pstmt = null;
        PreparedStatement pstmt2 = null;
        ResultSet rs = null;
 
        // insert an actor into the actor table
        String SQLInsertActor = "INSERT INTO actor(first_name,last_name) "
                + "VALUES(?,?)";
 
        // assign actor to a film
        String SQLAssignActor = "INSERT INTO film_actor(actor_id,film_id) "
                + "VALUES(?,?)";
 
        int actorId = 0;
        try {
            // connect to the database
            conn = connect();
            conn.setAutoCommit(false);
 
            // add actor
            pstmt = conn.prepareStatement(SQLInsertActor,
                    Statement.RETURN_GENERATED_KEYS);
 
            pstmt.setString(1, actor.getFirstName());
            pstmt.setString(2, actor.getLastName());
 
            int affectedRows = pstmt.executeUpdate();
 
            if (affectedRows > 0) {
                // get actor id
                rs = pstmt.getGeneratedKeys();
 
                if (rs.next()) {
                    actorId = rs.getInt(1);
                    if (actorId > 0) {
                        pstmt2 = conn.prepareStatement(SQLAssignActor);
                        pstmt2.setInt(1, actorId);
                        pstmt2.setInt(2, filmId);
                        pstmt2.executeUpdate();
                    }
                }
            } else {
                // rollback the transaction if the insert failed
                conn.rollback();
            }
 
            // commit the transaction if everything is fine
            conn.commit();
 
            System.out.println(
                    String.format("The actor was inserted with id %d and "
                            + "assigned to the film %d", actorId, filmId));
 
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
            // roll back the transaction
            System.out.println("Rolling back the transaction...");
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }
 
        } finally {
            this.close(rs)
                    .close(pstmt)
                    .close(pstmt2)
                    .close(conn);
        }
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        App app = new App();
        // OK transaction
         app.addActorAndAssignFilm(new Actor("Bruce", "Lee"), 1);
        
        // Failed transaction
        // app.addActorAndAssignFilm(new Actor("Lily", "Lee"), 9999);
    }
}

How the App class works.

The connect() method establishes a connection to the dvdrental database and returns a Connection object.

The close() method closes a closable object such as Resultset, Statement, and Connection.

The addActorAndAssignFilm() method inserts a new actor and assigns a film to the actor within a transaction.

  1. First, insert a new actor into the actor table.
  2. Next, get the id of the newly inserted actor
  3. Then, assign the actor to a film by inserting a new row into the film_actor table.
  4. After that, if both step 2 and 3 succeeded, commit the transaction. Otherwise, rollback the transaction
  5. Finally, close the ResultSet, PreparedStatement, and Connection objects.

If we execute the program with the first scenario, we get the following result:

1
2
3
run:
The actor was inserted with id 217 and assigned to the film 1
BUILD SUCCESSFUL (total time: 2 seconds)

We can verify it by querying the actor table:

1
2
3
4
5
6
7
8
SELECT
actor_id,
first_name,
last_name
FROM
actor
ORDER BY
actor_id DESC;

postgresql jdbc transaction example

and also the film_actor table:

1
2
3
4
5
6
7
SELECT
actor_id,
film_id
FROM
film_actor
WHERE
actor_id = 217;

postgresql jdbc transaction film_actor table

Now if we insert a new actor and assign her to a film that does not exist, it issues the following error messages:

1
2
3
4
5
run:
ERROR: insert or update on table "film_actor" violates foreign key constraint "film_actor_film_id_fkey"
  Detail: Key (film_id)=(9999) is not present in table "film".
Rolling back the transaction...
BUILD SUCCESSFUL (total time: 0 seconds)

The transaction is rolled back and nothing is inserted into the actor and film_actor tables.

In this tutorial, you have learned how to perform a transaction to ensure the integrity of data in the PostgreSQL database using JDBC transaction API.

Previous Tutorial: How To Delete Data From A PostgreSQL Table Using JDBC

PostgreSQL Quick Start

  • What is PostgreSQL?
  • Install PostgreSQL
  • Connect to Database
  • Download PostgreSQL Sample Database
  • Load Sample Database
  • Explore Server and Database Objects

PostgreSQL Fundamentals

  • PostgreSQL Select
  • PostgreSQL Order By
  • PostgreSQL Select Distinct
  • PostgreSQL Where
  • PostgreSQL LIMIT
  • PostgreSQL IN
  • PostgreSQL Between
  • PostgreSQL Like
  • PostgreSQL Inner Join
  • PostgreSQL Left Join
  • PostgreSQL Full Outer Join
  • PostgreSQL Cross Join
  • PostgreSQL Natural Join
  • PostgreSQL Group By
  • PostgreSQL Having
  • PostgreSQL Union
  • PostgreSQL Intersect
  • PostgreSQL Except
  • PostgreSQL Subquery
  • PostgreSQL Insert
  • PostgreSQL Update
  • PostgreSQL Delete
  • PostgreSQL Data Types
  • PostgreSQL Create Table
  • PostgreSQL Alter Table
  • PostgreSQL Drop Table
  • PostgreSQL Truncate Table
  • PostgreSQL CHECK Constraint
  • PostgreSQL Not-Null Constraint
  • PostgreSQL Foreign Key
  • PostgreSQL Primary Key
  • PostgreSQL UNIQUE Constraint

About PostgreSQL Tutorial

PostgreSQLTutorial.com is a website dedicated to developers and database administrators who are working on PostgreSQL database management system.

We constantly publish useful PostgreSQL tutorials to keep you up-to-date with the latest PostgreSQL features and technologies. All PostgreSQL tutorials are simple, easy-to-follow and practical.

Recent PostgreSQL Tutorials

  • PostgreSQL Recursive View
  • Learn PostgreSQL Recursive Query By Example
  • Creating Updatable Views Using the WITH CHECK OPTION Clause
  • PostgreSQL Upsert Using INSERT ON CONFLICT statement
  • How to Generate a Random Number in A Range
  • Using PostgreSQL ADD COLUMN to Add One or More Columns To a Table
  • PostgreSQL Character Types: CHAR, VARCHAR, and TEXT
  • Using PostgreSQL SERIAL To Create Auto-increment Column
  • PostgreSQL Boolean Data Type with Practical Examples
  • Understanding PostgreSQL Timestamp Data Types

More Tutorials

  • PostgreSQL PHP
  • PostgreSQL Python
  • PostgreSQL JDBC
  • PostgreSQL Functions
  • PostgreSQL Resources

Site Info

  • Home
  • About Us
  • Contact Us
  • Privacy Policy

Copyright © 2016 by PostgreSQL Tutorial Website. All Rights Reserved.