I am trying to use optimistic locking using the version field and no exception is being thrown when I call the save from the jpa repository. I am new to Spring and hibernate and I am worried that I am setting it up incorrectly.
The libraries i am using are:
hibernate4-maven-plugin version 1.0.2
hibernate-jpa02.0 1.0.1
spring-data-jpa version 1.3.4
So my entity is set up like this:
@Entity
public class MyEntity
{
@Id
protected Long id;
@Version
protected Long version;
protected String name;
public Long getVersion()
{
return version;
}
public void setVersion(Long version)
{
this.version = version;
}
public Long getVersion()
{
return version;
}
public void setVersion(Long version)
{
this.version = version;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(Long id)
{
this.name = name;
}
}
I pass the version through to the client through my dto and pass it back when i do a save in my MyEntityStoreDao:
@Repository
public class MyEntityStoreDao extends BaseDao<MyEntityStoreDao>
{
private RepositoryManager myRepoManager;
@Autowired
public void setMyRepo(MyEntityRepository myRepo)
{
this.myRepo = myRepo;
}
public MyEntity save(MyEntityDTO dtoToUpdate)
{
Session session = this.Session();
MyEntity myEntity = new MyEntity();
if(dtoToUpdate.getId() > 0) {
myEntity = (MyEntity) session.get(MyEntity.class, dtoToUpdate.getId())
}
myEntity.setName(dtoToUpdate.getName());
MyEntity result = this.myRepo.save(myEntity);
this.repositoryManager.flush(myRepo);
}
}
The repositoryManager is in the BaseDao and is using the org.springframework.data.jpa.repository.JpaRepository
.
The version is being updated correctly and incrementing. But when i do an update, I expect when the version being passed through from the DTO to save in the MyEntityStoreDao to not match what is in the database, it would throw a StaleStateException or OptmisticLockingException.
I checked and the versions do not match but the save still occurs. Any help on why this is happening? Thanks