enter image description here this img is user table and example tuple here,
I want to use sql query "SELECT MAX(KEY_NAME) FROM USER;" and right here enter image description here So in java, I wrote jpa query but I met ERROR 16148
2023-02-01 20:58:51.668 ERROR 16148 --- [nio-8080-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: Type specified for TypedQuery [gdsc.toypj.dutchpayit.domain.User] is incompatible with query return type [class java.lang.Long]; nested exception is java.lang.IllegalArgumentException: Type specified for TypedQuery [gdsc.toypj.dutchpayit.domain.User] is incompatible with query return type [class java.lang.Long]] with root cause
here my source
UserRepository.java
public User findOneUser() {
return em.createQuery("select MAX(r.id) from User r", User.class)
.getSingleResult();
}
User.java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "key_name")
private Long id;
private String name;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<Menu> menuList = new ArrayList<>();
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
private List<People> peopleList = new ArrayList<>();
public static User addUser(String name){
User user = new User();
user.setName(name);
return user;
}
UserService.java
@Transactional
public User OneUser(){
User user = userRepository.findOneUser();
return user;
}
UserController.java
@GetMapping("/get/one")
public ResponseEntity getOneUser(){
User user = userService.OneUser();
return ResponseEntity.status(HttpStatus.OK).body(new SuccessResponse(200,user));
}
I've been trying more than 3 hours..
in UserRepository.java, I tried them and error in everything.
em.createQuery("select MAX(r.Key_name) from User r", User.class)
em.createQuery("select id from User", User.class)
oh this is worked
return em.createQuery("select r from User r", User.class)
.getResultList();
why only "select r" is working I don't know!!!!
CodePudding user response:
The error comes from the TypedQuery defined to return the User
object.
You can try and change the TypedQuery to Long
or create another query that will return the User as an object.
You can go with something similar like this:
select r from User r where r.id = (select MAX(r.id) from User r)