Kalyan Pradhan
Kalyan Pradhan

Reputation: 1475

How to ensure every database transaction in `Spring-Data` is executed sequentially?

Recently I have ran into a problem while using Spring-Data,

The situation is as described below:

As there are multiple transactions going on simultaneously, there is possibility that same record of wallet table is being accessed by more than one user as described below:

For example

One user is performing some transaction for which the commission is being credited to the Admin user's (Parent user's) Wallet,

And at the same time the Admin user is performing a debit operation upon his own wallet.

So in this situation the transaction which is performed at last, will be persisted in to the database.

So is there any method by which I can make one transaction wait for another?

Following is an example of how the user and wallet tables are related

@Entity(name = "user")
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.NOT_SUPPORTED)
public class User implements UserDetails, Comparable<User> {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @Column(name = "user_id")
    @OrderColumn
    private Long Id;
    @OneToOne(fetch = FetchType.LAZY)
    @OrderColumn
    private Wallet wallet;
    @OneToOne
    @OrderColumn
    private User parentUser;

.........Getters and setters........
}


@Entity
public class Wallet {

    @Id
    @GeneratedValue
    @OrderColumn
    private Long Id;
    @OneToOne()
    @OrderColumn
    private User user;

    //Other values.
    ....... GETTERS AND SETTERS.......
}

In short I need to make a transaction wait for another transaction to get completed, if there is one already.

I have tried out isolation and propagation but it did not produce the required result.

Is it possible in spring data to make transactions wait for each other?

Thanks in advance.

Upvotes: 3

Views: 981

Answers (1)

KayV
KayV

Reputation: 13835

Making the Propagation as REQUIRED can serve the purpose here.

@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED)

Upvotes: 2

Related Questions