Why does rollback occur in spring jpa after first find - spring

I'm not sure why rollback occurs after the first find query. The first query perfectly works fine, but rollback constantly occurs if I try to do a query again.
This is the Controller.
//....
#GetMapping("/s-id/{s-id}")
public ResponseEntity<DefaultResponseDto<Object>> findManyBySId(HttpServletRequest servletRequest,
#PathVariable(name = "s-id")
String sId) {
// ...
List<Member> members = memberService.findManyBySpotrightId(spotrightId);
// ....
}
//...
This is the Service.
#Transactional(readOnly = true)
public List<Member> findManyBySId(String spotrightId) {
try {
return memberRepository.findBySpotrightIdContainsAndIsDeletedIsFalse(spotrightId);
} catch (RuntimeException e) {
throw new CustomException(SERVER_ERROR);
}
}
This is the Repository.
public interface MemberRepository extends JpaRepository<Member, Long> {
List<Member> findBySIdContainsAndIsDeletedIsFalse(String sId);
}
This is the error message that I get in the console
2023-02-06 19:21:48.470 INFO 62504 --- [nio-8080-exec-9] c.s.s.common.aop.TraceAspect : [START] MemberService | findManyBySpotrightId null | sId = admin
2023-02-06 19:21:48.473 INFO 62504 --- [nio-8080-exec-9] c.s.s.common.aop.TraceAspect : [START] MemberRepository | findBySIdContainsAndIsDeletedIsFalse null
2023-02-06 19:21:48.485 INFO 62504 --- [nio-8080-exec-9] p6spy : #1675678908485 | took 1ms | rollback | connection 8| url jdbc:mysql://localhost:3306/spot?serverTimezone=UTC&characterEncoding=UTF-8
;
2023-02-06 19:21:48.498 ERROR 62504 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [\] did not match expected type [java.lang.String (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [\] did not match expected type [java.lang.String (n/a)]] with root cause
java.lang.IllegalArgumentException: Parameter value [\] did not match expected type [java.lang.String (n/a)]
Why does the rollback occur? And How do I fix this problem?

I found out that it is a bug from Hibernate. I fixed it by including #Param("sId") to parameter like below.
List<Member> findBySIdContainingAndIsDeletedIsFalse(#Param("sId") String sId);

Related

Problem with saving an object with rest template, Spring web app

So I'm building a flashcard app with Spring, JPA, MySQL and using Thymeleaf.
At first when i started building I only used MVC. All functionality for saving a new user, a new flashcard and a new topic worked.
Now I connected it with a project with a restcontroller and did some modifactions.
The problem is that I can't seem to save a new flashcard (although i can save a topic and a user)
Can someone spot where i've made a mistake?
(note. i have a JPARepository in the backend)
#Controller-class
//This does not work
#PostMapping("/save")
public String set(#ModelAttribute Flashcard flashcard){
restTemplate.postForObject("http://localhost:8081/api/card/save", flashcard, Flashcard.class);
return "redirect:/";
}
//this works
#PostMapping("/savePlayer")
public String savePlayer(#ModelAttribute Player player){
restTemplate.postForObject("http://localhost:8081/api/player/save", player, Player.class);
return "homepage";
}
**#RestController-class**
#PostMapping("/api/card/save")
public Flashcard createFlashcard(#RequestBody Flashcard flashcard) {
log.info("New Card added to FlashcardRepository - {}", flashcard);
return repository.save(flashcard);
}
**Flashcard-class**
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "card_id")
Long id;
String term;
String answer;
#ManyToOne
#JsonBackReference
#JoinColumn(name = "topic_id")
Topic topic;
Error message:
2022-07-15 10:17:41.555 WARN 2016 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2022-07-15 10:17:41.556 ERROR 2016 --- [nio-8081-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'topic_id' cannot be null
2022-07-15 10:17:41.608 ERROR 2016 --- [nio-8081-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

spring QueryExecutionRequestException

using spring jpa.
the repository:
public interface FacultyMemberImpl extends JpaRepository<FacultyMember,Long> {
#Query("SELECT e FROM FacultyMember e WHERE e.name =:name")
List<FacultyMember> getFacultyByName(#Param("name") String name);
#Transactional
#Modifying
#Query("UPDATE FacultyMember e SET e.name=:name, e.department=:department WHERE e.id=:id")
List<FacultyMember> updateFaculty(#Param("id") int id,#Param("name") String name,#Param("department") String department);
}
the error
2019-01-28 09:57:53.027 ERROR 14264 --- [nio-8181-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.facultyProject.faculty_project.dao.FacultyMember e SET e.name=:name, e.department=:department WHERE e.id=:id]; nested exception is java.lang.IllegalStateException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [UPDATE com.facultyProject.faculty_project.dao.FacultyMember e SET e.name=:name, e.department=:department WHERE e.id=:id]] with root cause

Spring boot design delete RESTful API through JPA got error

I need design delete API, but I got error. I still not get idea where was wrong.
Repository:
public interface ProductRepository extends JpaRepository<Product, Integer> {
#Modifying
#Query(nativeQuery=true, value = "delete from product where productid = ?1")
void deleteProductByProductID(int productID);
}
Controller:
#DeleteMapping(path = "/delete/{id}")
public #ResponseBody
void deleteProduct(#PathVariable("id")int productID) {
productRepository.deleteProductByProductID(productID);
}
API test error:
{
"timestamp": "2018-04-08T08:46:15.639+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet",
"path": "/v1/product/delete/30"
}
IDE error:
2018-04-08 01:36:26.890 WARN 13629 --- [nio-8080-exec-1]
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState:
S1009 2018-04-08 01:36:26.890 ERROR 13629 --- [nio-8080-exec-1]
o.h.engine.jdbc.spi.SqlExceptionHelper : Can not issue data
manipulation statements with executeQuery(). 2018-04-08 01:36:26.906
ERROR 13629 --- [nio-8080-exec-1]
o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for
servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.orm.jpa.JpaSystemException: could not extract
ResultSet; nested exception is
org.hibernate.exception.GenericJDBCException: could not extract
ResultSet] with root cause

Running a native insert query in spring boot

I am trying to run a simple insert query in spring boot but I am unable to do so.
Query:
#Modifying
#Query(value = "insert into Local(userId,name,address,pin) VALUES (:userId,:name,:address,:pin)", nativeQuery = true)
List < Local > insertattributes(#Param("userId")String userId,#Param("address") String address ,#Param("name")String name,#Param("pin") String pin);
Controller:
#RequestMapping("insertattributes/{userId}/{name}/{address}/{pin}")
#ResponseBody
public List < Local > insertAttributes(#PathVariable String userId, #PathVariable String name, #PathVariable String address, #PathVariable String pin) {
return localService.insertattributes(userId,name,address,pin);
}
Error:
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: S1009
o.h.engine.jdbc.spi.SqlExceptionHelper : Can not issue data manipulation statements with executeQuery().
[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet] with root cause
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
An insert statement doesn't return the inserted record. Since you're expecting a list to be returned executeQuery() is executed by Spring. What you want is the executiong of executeUpdate() which is only executed for void methods.
See also Cannot issue data manipulation statements with executeQuery()

Bean Initialization on condition fails after Spring boot version update to 2.0.1.Release

Unable to start the project After spring-boot-starter-parent version update from 1.5.9.RELEASE to 2.0.1.RELEASE. It was found that when we have a conditional bean initialization method the application is failing to start.
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- Previous version -->
<!-- <version>1.5.9.RELEASE</version> -->
<!-- Updated version -->
<version>2.0.1.RELEASE</version>
<relativePath />
</parent>
application.properties
host.enabled=false
DemoApplication.java
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
DemoClass.java
#Component
#EnableScheduling
public class DemoClass {
#Value("${host.enabled}")
private boolean enableHostName;
#Bean(name = "hostName")
public String getName() {
try {
if(enableHostName)
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "Unknown";
}
return null;
//return "";
}
#Autowired
#Qualifier("hostName")
String hostName;
#Scheduled(fixedRate = 3000)
public void print(){
System.out.println(hostName);
}
}
Console Log:
2018-04-11 17:59:32.584 WARN 24120 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoClass': Unsatisfied dependency expressed through field 'hostName'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value=hostName)}
2018-04-11 17:59:32.592 INFO 24120 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-04-11 17:59:32.620 INFO 24120 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-11 17:59:32.917 ERROR 24120 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field hostName in com.vjs.demo.DemoClass required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.
See here in spring boot 2.01 doesn't accept autowiring Null beans
because in your propertie file the value is set to false so the bean #Bean(name = "hostName") will always return a null String ,
Changing the return to empty or a sipmle value will fix the problem
like
#Bean(name = "hostName")
public String getName() {
try {
if(enableHostName)
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "Unknown";
}
return "Host name not enabled";
}

Resources