简体   繁体   中英

Set lock timeout programmatically Spring Boot JPA

I have

@Transactional(timeout = 600)
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerRepository customerRepository;

    @Override
    public void actOnCustomer(Long customerId) {
    ...

along with

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    Optional<Customer> findById(Long id);

The customer row seems to be getting locked, and the timeout value seems to be having the proper effect.

Now I want to be able to set the timeout value programmatically, and/or using my application.properties file . I've seen some examples of setting javax.persistence.lock.timeout in properties passed to an EntityManager 's find method, but I'm not sure of how best to incorporate EntityManager calls into a Spring repository, and it seems like there should be a more Spring-y way (like setting spring.jpa.properties.javax.persistence.lock.timeout=600 in application.properties, which doesn't seem to work).

So how do I do this?

I ended up adding

@Autowired
private Environment env;

@PostConstruct
public void configureJpaTransactionManager() {
    ((JpaTransactionManager) this.platformTransactionManager).setDefaultTimeout(
                Integer.parseInt(env.getProperty("transaction.timeout", "3")));
}

to my @SpringBootApplication -annotated main class, which seemed to do the job. Not sure it is the best way. ("transaction.timeout" is a property name I made up).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM