I know it's another similar question, but I can't answer it myself, that's why I'm writing to you for help.
I try to create my own @Query and returns a conversion error on two occasions. My guess is there is a problem with the service, but this is where my knowledge ends.
Here is my code:
Main entity
@Data @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String city; private Date startDate; private boolean stat; public User() { } public User(String name, String city, Date startDate, boolean stat) { this.name = name; this.city = city; this.startDate = startDate; this.stat = stat; } }
2.Second model
public class UserName {
private String firstname;
public UserName() {
}
public UserName(String firstname) {
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
3.Third model
public class UserCount {
private String city;
private int count;
public UserCount() {
}
public UserCount(String city, int count) {
this.city = city;
this.count = count;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
Repository
@Repository public interface UserRepository extends JpaRepository<User, Long> {
@Query("select p from User p") //1.it's work List<User> getAll(); @Query("select u from User u where u.name like %?1") //2.it's work List<User> findByFirstnameEndsWith(String firstname); @Query("select u.name from User u ") //3. don't work List<UserName> getNameUsers(); // this SQL working in database console H2 // SELECT city, count(*) FROM USERS WHERE stat = true GROUP BY city @Query("select u.city, count (u) from User u where u.stat = true group by u.city") //3. don't work List<UserCount> getOwnQuery();
}
Service
@Service public class UserService { @Autowired private UserRepository repo;
public List<UserName> getN (){ return repo.getNameUsers(); } public List<UserCount> getC(){ return repo.getOwnQuery(); }
}
Controller
@Controller public class MyController {
@Autowired private UserRepository repo; @Autowired private UserService repoService; @GetMapping("/") //1.it's work ResponseEntity<List<User>> getAllCity(Pageable page){ return ResponseEntity.ok(repo.getAll()); } @GetMapping("/s") //2.it's work ResponseEntity<List<User>> getAllUsers(Pageable page){ return ResponseEntity.ok(repo.findByFirstnameEndsWith("Seba")); } @GetMapping("/f") ///3.don't work ResponseEntity<List<UserName> >getUsersName(Pageable page){ return ResponseEntity.ok(repoService.getN()); } @GetMapping("/c") ///4.don't work ResponseEntity<List<UserCount> >getUsersCount(Pageable page){ return ResponseEntity.ok(repoService.getC()); }
}
It also adds source code on GitHub
sorry i didn't add the error code