I have a situation where I have to make a choice between two options and it's not clear for me what is the difference between that options. I will be very thankful if somebody could explain to me which one should I choose and why. Long story short I have a simple JPA entity (Kotlin language):
@Entity
@Table(name = "account")
data class AccountEntity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long,
var balance: Int,
@ManyToOne
var accountType: AccountTypeEntity
)
And in business-logic layer I want to have a method for updating account balance by its accountId. Basically I need to load account entity by id, then set new balance and lastly use save method which is provided by Hibernate. But I also found the fact that I don't need to call save method in explicit form if my method will be annotated with @transactional. So from that point I have two options
First one
fun updateAccountBalance(id: Long, balance: Int) {
val account = accountRepository.findById(id).orElseThrow { RuntimeException("No account with id=$id found") }
account.balance = balance
accountRepository.save(account)
}
Second one
@Transactional
fun updateAccountBalance(id: Long, balance: Int) {
val account = accountRepository.findById(id).orElseThrow { RuntimeException("No account with id=$id found") }
account.balance = balance
}
Firstly, for me it's not clear what will be the difference of those options in terms of database. Could you please clarify it?
Secondly, I think that in such method I don't really need TRANSACTION (in terms of database) at all because I make only one 'write' operation and for me it looks redundant to use to avoid calling hibernate save method in explicit form. But may be I'm wrong and there are some reasons to use transaction even here. So please correct me.