spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
@Configuration
@EnableTransactionManagement
public class TransactionConfiguration {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory);
return tm;
}
}
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Transactional
public void updateProductPrice(Long productId, double newPrice) {
Product product = productRepository.findById(productId).orElseThrow(() -> new ProductNotFoundException(productId));
product.setPrice(newPrice);
productRepository.save(product);
}
}
@Entity
public class Product {
@Version
private int version;
}
@Service
public class ProductService {
@Autowired
private EntityManager entityManager;
@Transactional
public void updateProductPriceWithPessimisticLock(Long productId, double newPrice) {
Product product = entityManager.find(Product.class, productId, LockModeType.PESSIMISTIC_WRITE);
product.setPrice(newPrice);
}
}