How to properly use Locking or Transactions to prevent duplicates using Spring Data -


what best way check if record exists , if doesn't, create (avoiding duplicates)?

keep in mind distributed application running across many application servers.

i'm trying avoid these:

a simple example:

person.java

@entity public class person {     @id    @generatedvalue    private long id;     private string firstname;     private string lastname;     //getters , setters omitted  } 

personrepository.java

public interface personrepository extends crudrepository<person, long>{     public person findbyfirstname(string firstname);  } 

some method

public void somemethod() {         person john = new person();         john.setfirstname("john");         john.setlastname("doe");         if(personrepo.findbyfirstname(john.getfirstname()) == null){             personrepo.save(john);         }else{             //don't save person         }    } 

clearly code stands, there chance person inserted in database in between time checked if exists , when insert myself. duplicate created.

how should avoid this?

based on initial research, perhaps combination of

but exact configuration i'm unsure of. guidance appreciated. reiterate, application distributed across multiple servers must still work in highly-available, distributed environment.

for inserts: if want prevent same recordsto persisted, may want take precoutions on db side. in example, if firstname should unique, define unique index on column, or agroup of colunsd should unique, , let db handle check, insert & exception if you're inserting record that's inserted.

for updates: use @version (javax.persistence.version) annotation this:

@version private long version; 

define version column in tables, hibernate or other orm automatically populate value & verison clause when entity updated. if try update old entity, prevent this. careful, doesn't throw exception, return update count 0, may want check this.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -