参数值 [2] 与预期类型不匹配 [com.cityBike.app.model.User

Parameter value [2] did not match expected type [com.cityBike.app.model.User

我收到错误

java.lang.IllegalArgumentException: Parameter value [2] did not match expected type [com.cityBike.app.model.User (n/a)] at org.hibernate.jpa.spi.BaseQueryImpl.validateBinding(BaseQueryImpl.java:885) at org.hibernate.jpa.internal.QueryImpl.access[=14=]0(QueryImpl.java:80) at org.hibernate.jpa.internal.QueryImpl$ParameterRegistrationImpl.bindValue(QueryImpl.java:248) at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:631) at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:180) at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49) at com.cityBike.app.service.RentService.getAllByUser(RentService.java:22)

下面是我的代码片段,我该如何解决这个问题?

文件Rent.java

@Entity
@Table(name="Rent")
public class Rent implements Serializable {

    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  
    @Column(name = "id")  
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "start_id")
    private Station start_id;

    @ManyToOne
    @JoinColumn(name = "meta_id")
    private Station meta_id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user_id; 
    ... 

文件User.java

@Entity  
@Table(name="Users")
public class User implements Serializable {

    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  
    @Column(name = "id")  
    private Integer id;

    @Column(name = "login")
    private String login;
...

文件RentService.java

@Service
public class RentService {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public List<Rent> getAllByUser(int user_id){
            System.out.println(user_id);
            List<Rent> result = em.createQuery("from Rent a where a.user_id = :user_id", Rent.class).setParameter("user_id", user_id).getResultList();
            System.out.println(result);
        return result;
    }
}

我应该补充一点,"user_id" 在控制台上显示时是正确的,因为它有这样的数值 ex。 2 或 3。 请指导和帮助。

Rent.user_id 的类型是用户,因此当您将 int 传递给查询时

from Rent a where a.user_id = :user_id

您正在比较 Userint

相反,您需要编写

from Rent a where a.user_id.id = :user_id

我建议将 Rent.user_id 重命名为 Rent.user 以避免此类错误。

您可以使用这个查询:-

Rent class 中的 user_id 不是整数,它是 User 类型的对象,因此您必须使用 User 对象它是 id

List<Rent> result = em.createQuery("from Rent a where a.user_id = :user_id", Rent.class).setParameter("user_id", em.getReference(User.class, user_id)).getResultList();

或者你可以这样写:-

List<Rent> result = em.createQuery("from Rent a where a.user_id.id = :user_id",Rent.class).setParameter("user_id", user_id).getResultList();