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

时间:2016-01-17 11:48:02

标签: java hibernate jpa createquery

我收到错误

  

java.lang.IllegalArgumentException:参数值[2]与预期类型[com.cityBike.app.model.User(n / a)]不匹配       在org.hibernate.jpa.spi.BaseQueryImpl.validateBinding(BaseQueryImpl.java:885)       在org.hibernate.jpa.internal.QueryImpl.access $ 000(QueryImpl.java:80)       在org.hibernate.jpa.internal.QueryImpl $ ParameterRegistrationImpl.bindValue(QueryImpl.java:248)       在org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:631)       在org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:180)       在org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:49)       在com.cityBike.app.service.RentService.getAllByUser(RentService.java:22)

以下是我的代码段,如何解决此问题?

File 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; 
    ... 

File 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;
...

File 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;
    }
}

我应该添加&#34; user_id&#34;当在控制台上显示时是正确的,因为它具有这样的数值ex。 2或3。 请指导和帮助。

2 个答案:

答案 0 :(得分:7)

当您将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以避免此类错误。

答案 1 :(得分:1)

您可以使用此查询: -

user_id类中的Rent并不是User类型的对象,因此您必须使用User对象获取它的身份

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();