I want to find the last inserted item from table "product" with Spring-Data-JPA (Hibernate implementation) and QueryDSL(type safe) to generate SQL: SELECT * FROM product ORDER BY id DESC LIMIT 1
I have call findLast() from Service with @Transactional and want to setLockMode(LockModeType.PESSIMISTIC_WRITE) and to add "SELECT .. FOR UPDATE" in this SQL query.
public class ProductRepositoryImpl extends QueryDslRepositorySupport implements ProductRepositoryCustom {
public ProductRepositoryImpl() {
super(Product.class);
}
//SELECT * FROM PRODUCTS ORDER BY ID DESC LIMIT 1
@Override
public Product findLast() {
QProduct product = QProduct.product;
return from(product).orderBy(product.id.desc()).limit(1L).fetchOne();
}
}
This is the generated SQL
Hibernate: select * from ( select product0_.id as id11, product0_.description as description21, product0_.price as price31, product0_.productStatus as productStatus41, product0_.quantity as quantity51 from PRODUCTS product0 order by product0.id desc ) where rownum <= ?
The question: What is the best way to add setLockMode() in repository extending org.springframework.data.jpa.repository.support.QueryDslRepositorySupport?
I have try this but it return Object and needs to cast (Product):
getQuerydsl().createQuery(product)
.setLockMode(LockModeType.PESSIMISTIC_WRITE).orderBy(product.id.desc()).limit(1L).fetchOne();
rownum <= 1- Naroslimit()and tell it to callfetch()orfetchResults(). Does the generated SQL work as you would expect? - Naros