Could not extract ResultSet when performing customized native query - java

I am using Spring Data JPA and I want to encapsulate a method which performs specific SQL. I do it in the following matter:
#Component
public interface UserRepository extends CrudRepository<User, String> {
#Query(
value = "delete from User u where u.alias = :alias",
nativeQuery = true
)
void deleteUserByAlias(#Param("alias") String alias);
}
However, I got the following message as the result:
{
"timestamp": "2018-12-11T15:54:54.627+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet",
"path": "/user/delete"
}
So where is the problem?

If your method is already Transactional , then please use transactional on repository method also
#Component
public interface UserRepository extends CrudRepository<User, String> {
#Query(
value = "delete from User u where u.alias = :alias",
nativeQuery = true
)
#Modifying
#Transactional
void deleteUserByAlias(#Param("alias") String alias);
}

#Repository
#Transactional
interface OrderRepository: JpaRepository<Order, OrderIdentity>{
#Query("SELECT * FROM orders WHERE id=:id",nativeQuery = true)
fun findBy(#Param("id") id: String): List<OrderEvent>
#Modifying
#Query("DELETE FROM orders WHERE id=:id", nativeQuery = true)
fun deleteFor(#Param("id") id: String)
}
By using #Modifying on method and #Transactional on Repository error will be resolved.

your class should be like this:
#Component
public interface UserRepository extends CrudRepository<User, String> {
#Query(
value = "delete from User u where u.alias = :alias",
nativeQuery = true
)
#Modifying
void deleteUserByAlias(#Param("alias") String alias);
}
As you can see I am using #Modifying, for more information take a look to this https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.modifying-queries

Not answer my question directly, but found a workaround to remove record based on other attribute but not ID.
According to answer from this thread,
Derivation of delete queries using given method name is supported
starting with version 1.6.0.RC1 of Spring Data JPA. The keywords
remove and delete are supported. As return value one can choose
between the number or a list of removed entities.
Long removeByLastname(String lastname);
List deleteByLastname(String lastname);
I can write
#Transactional
void deleteByAlias(String alias);
at UserRepository to achieve the goal.
I won't accept this answer and open for any further contribution.

Check the param you are passing is not null. it worked for me.

Related

How to pass path variable to JPA repository from controller

How to pass path variable to JPA repository from controller.
I have a controller here and from the front End I am getting one varaible.
here is my controller :
#GetMapping("/getTransictionsAndInstruments/{id}")
public List<TransictionProjection> getTransitionInstrument(#PathVariable Long id){
return transictionrepository.getTransictionsAndInstruments();
}
Based on this id i want some alteration in my reult. I ahve already have on query and want to use this id in repo. so how to pass that in repo.
#Repository
public interface TransictionRepository extends JpaRepository<Transictions, Long>{
#Query(value = "SELECT transiction.user_id, transiction.quantity, transiction.instrument_name, transiction.Price, instrument.LTP, instrument.jo_caps FROM instrument INNER JOIN transiction ON instrument.instrument = transiction.instrument_name where transiction.User= id", nativeQuery = true)
List<TransictionProjection> getTransictionsAndInstruments();
}
I want to include this line in my query where transiction.User= id
Any help here that how to achive this.
I think this can be achieved by following:
Adding :id in your native query and passing id in function.
#Query(value = "SELECT transiction.user_id, transiction.quantity, transiction.instrument_name,
transiction.Price, instrument.LTP, instrument.jo_caps FROM instrument INNER JOIN transiction ON instrument.instrument = transiction.instrument_name
where transiction.User= :id", nativeQuery = true)
List<TransictionProjection> getTransictionsAndInstruments(Long id);

Spring Data JPA - Creating custom query method generator

In Spring Data JPA we can define a repository interface extending Repository and write a custom method.
If this method follows special syntax, Spring Data will generate the method body automatically.
For example (from the documentation):
interface PersonRepository extends Repository<Person, Long> {
List<Person> findByLastname(String lastname);
}
Is there a way to customize the method generation code to introduce new keywords into the syntax?
For example:
Person findExactlyOneById(Long id);
This method would either return the entity or throw a custom exception.
I know I can customize specific repositories as well as the base repository and achieve the effect from the above example, but I'm specifically asking for the automatic method of body generation.
Is there an extension point designed in the framework? Or is the only option to change the source code?
In your case, you can always use CrudRepository.findById(Long id) or JpaRepository.getOne(Long id).
I would suggest inheriting from the JpaRepository class because all types of repositories are included.
You can set nativeQuery = true in the #Query annotation from a Repository class like this:
public static final String FIND_PROJECTS = "SELECT projectId, projectName FROM projects";
#Query(value = FIND_PROJECTS, nativeQuery = true)
public List<Object[]> findProjects();
It's probably worth looking at the Spring data docs as well.
Some more example
1.
public interface UserRepository extends JpaRepository<User, Long> {
#Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}

Spring JPA could not handle multiple transactions in one thread properly

I have the following code fragment. After I invoke BatchSettleService.batchSettleWork(Array.asList([1,2,3])). I found that the account balance only reduce 1 in DB. The debug result is every time accountRepository.findByIdForUpdate(2) returns the original Account without any change operated in the past loops. I have tried Isolation.SERIALIZABLE level but the result is the same. The data base I am using is MySQL 5.7.20 InnoDb Engine. The JPA implemention is Hibernate. I am expecting the account balance to be reduced 3. Is there something wrong with my understanding of transaction? Thank you in advance!
#Service
public class BatchSettleService {
private Logger logger = LoggerFactory.getLogger(getClass());
#Autowired
private WorkSettleService workSettleService;
public List<WorkSettleResponse> batchSettleWork(List<Long> workIds) {
List<WorkSettleResponse> results= new ArrayList<>();
for(Long workId:workIds) {
try {
results.add(workSettleService.settleWork(new WorkSettleRequest(workId)));
} catch (WrappedException e) {
results.add(new WorkSettleResponse(workId,e.getErrCode(),e.getMessage()));
logger.error("Settle work failed for {}",workId,e);
}
}
return results;
}
}
public class WorkSettleService{
#Autowired
private AccountRepository accountRepository;
#Transactional(rollbackFor= {WorkSettleException.class,RuntimeException.class},propagation=Propagation.REQUIRES_NEW)
public WorkSettleResponse settleWork(WorkSettleRequest req){
Account account = accountRepository.findByIdForUpdate(2);
Integer balance = account .getBalance();
accountRepository.updateBalanceById(account.getId(),balance-1)
}
}
public interface AccountRepository extends Repository<Account, Integer> {
public Account findById(Integer id);
#Lock(LockModeType.PESSIMISTIC_WRITE)
#Query("select ac from Account a where a.id = ?1")
public Account findByIdForUpdate(Integer id);
#Modifying
#Query("update Account a set a.balance = ?2 where a.id = ?1")
public int updateBalanceById(Integer id,Integer balance);
}
This case has been solved.
Using account.setBalance(balance-1) instead of accountRepository.updateBalanceById(account.getId(),balance-1).
I don't know why #Modifying annoation doesn't update the EM cache while #Query fetch data from EM cache, a bit strage for Spring JPA implemention.

Spring Data JPA how to pass a variable by using #repository

Thank U, guys! I have found the solution:
#Repository
public interface BookRepository extends JpaRepository<Book, Integer>{
#Query(value = "select * from Book where find_in_set(:market,market)", nativeQuery = true)
public List<Book> findBooksByMarcket(#Param("market") String market);
}
Original question
I'm using the #Query annotation to create queries by using the JPA query language and to bind these queries directly to the methods of my repository interface.
My database is created correctly and I'm successful to create some queries except this one:
#Repository
public interface BookRepository extends JpaRepository<Book, Integer>{
#Query("select b from Book b where find_in_set(:market,b.market)")
public List<Book> findBooksByMarcket(#Param("market") String market);
}
I can get the correct result by using the find_in_set function when I check it though MySql. But I cannot reach to pass a variable in java. I have searched though the internet but I cannot find the correct format for it.
please help and thank you guys!
A quick solution is to transform the JPQL query to a native query (by setting the nativeQuery flag to true):
#Query(value = "select * from Book b where find_in_set(:market,b.market)", nativeQuery = true)
public List<Book> findBooksByMarcket(#Param("market") String market);
If you have a custom MySQL function and want to utilize it in a JPA repository, please take a look at tip 1
There is another way to do it using CriteriaBuilder (I used this mechanism along with JPA specification): tip 2
Key words for your search: custom db function, JPA specification, CriteriaBuilder, Criteria
Try this
#Repository
public interface BookRepository extends JpaRepository<Book, Integer>{
#Query("select b from Book b where find_in_set(?1,b.market)")
public List<Book> findBooksByMarcket(String market);
}

JPA findBy field ignore case

How do I make findByIn search using IgnoreCase of <Field>?
I tried to use findByNameIgnoreCaseIn and findByNameInIgnoreCase with no result.
DB is Postgresql.
#Repository
public interface UserRepository {
List<User> findByNameIgnoreCaseIn(List<String> userNames);
}
Try something like this:
List<User> findByNameInIgnoreCase(List<String> userNames);
As I understood IgnoreCase is not supported with In key, so I changed code this way:
#Repository
public interface UserRepository {
#Query("select user from SysUser user where upper(name) in :userNames")
List<SysUser> findByNameIgnoreCaseIn(#Param("userNames") List<String> userNames);
}
and previously upper case userNames values.

Categories