InvalidDataAccessApiUsageException with spring + jpa - PullRequest
0 голосов
/ 02 апреля 2020

В настоящее время я учусь использовать пружину, пока создаю простую защиту. Проект заключается в создании вымышленной сети, в которой психологи и пациенты могут взаимодействовать друг с другом.

Прямо сейчас я пытаюсь создать страницу администратора, где вы можете увидеть совокупность пользователей каждого типа, психолога и пациентов, но в пакете по 10 человек, потому что, возможно, их будет слишком много. видеть, и было бы больно прокручивать все страницы вниз, чтобы увидеть их.

Дело в том, что по какой-то странной причине, когда Spring пытается определить тип параметра запроса имени, он говорит это является целым числом, но я использую только длинные типы.

Не могли бы вы объяснить, что я делаю здесь неправильно?

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [30] did not match expected type [java.lang.Integer (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [30] did not match expected type [java.lang.Integer (n/a)]] with root cause

java.lang.IllegalArgumentException: Parameter value [30] did not match expected type [java.lang.Integer (n/a)]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:27) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]

Мой текущий контроллер, где это происходит, выглядит следующим образом:

package beginner.project.controller;

import java.util.ArrayList;
import java.util.List;
import java.lang.Long;

import javax.persistence.EntityManager;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import es.fdi.ucm.ucmh.model.User;
import es.fdi.ucm.ucmh.model.repositories.UserRepository;

@Controller
public class AdminController {
    private static Logger log = LogManager.getLogger(AdminController.class);
    private final String PATIENT_TYPE = "USER";
    private final String PSYCHOLOGIST_TYPE = "PSY";
    private Long lastPatUser;
    private Long lastPsyUser;
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/admin/{adminId}")
    public String getAdminPage(@PathVariable Long adminId, Model model) {
        User admin = entityManager.find(User.class, adminId);

        if(admin == null) {
            return "404";
        }

        lastPatUser = 30l;
        lastPsyUser = 10l;

        List<User> patient_List = userRepository.getUserListMoreThan(PATIENT_TYPE, lastPatUser);
        List<User> psychologist_List = userRepository.getUserListMoreThan(PSYCHOLOGIST_TYPE, lastPsyUser);

        lastPatUser += 10l;
        lastPsyUser += 10l;

        model.addAttribute("patients_list", patient_List);
        model.addAttribute("psychologist_list", psychologist_List);
        model.addAttribute("admin", admin);

        return "admin";
    }

Мой репозиторий имеет следующую структуру:

package beginner.project.model.repositories;

import java.util.List;
import java.lang.Long;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import es.fdi.ucm.ucmh.model.User;

@Transactional(readOnly = true)
public interface UserRepository extends JpaRepository<User, Long> {



    /**
     * This method will query a list of users to the embedded DB
     * @param userType a string representing the user type we want to query
     * @return A list of users
     * */
    //public List<User> getUserList(String userType);
    public List<User> getUserListMoreThan(String userType, Long lastUser);
    public List<User> getUserListLessThan(String userType, Long lastUser);

    /**
     * This method will query a list of users that match the first name
     * @param userFirstName a string representing the user first name
     * @return A list of users
     * */
    public List<User> getUserByFirstName(String userFirstName);
}

А мой пользовательский объект:

package beginner.project.model;

import java.util.Collection;
import java.lang.Long;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

@Entity
@NamedQueries({
    @NamedQuery(name = "User.getUserListMoreThan", 
                query = "SELECT u "
                        + "FROM User u "
                        + "WHERE u.type = :userType AND (u.id >= (:lastUser + 1) AND u.id < (:lastUser + 11)) "
                        + "ORDER BY u.id ASC ")
})
public class User {
    //------------Atributos---------------------
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String firstName;
    private String lastName;
    private String mail;
    private String password;
    private String phoneNumber;
    private String type;

...