jpql查询构造,值1与预期类型不匹配

时间:2018-01-05 13:36:47

标签: java mysql rest jpa jpql

您好我有两个表格

1。Person table

2。Phone numer table

我正在尝试实现此类查询

SELECT * FROM jobs.phonenumber where Person_ID='1';

但是在jpql中。

我试图做出类似的事情:

String query="SELECT p1 FROM PhoneNumber p1 WHERE p1.person=:id;

以下是我的实体类的示例:

@Entity
public class PhoneNumber {
    @Id
    @GeneratedValue
    @Column(name = "phoneId")
    private long id;
    @Column(name = "phoneNumber")
    private int number;
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "Person_ID")
    private Person person;


@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "personId")
    private long id;
    @Column(name = "personName")
    private String name;
    @Column(name = "personAge")
    private int age;
    @OneToMany(mappedBy = "person")
    private List<PhoneNumber> phones;

我有一个错误:参数值1与预期类型不匹配[model.Person(n / a)]

这是我的方法:

@Path("{id}/phones")
@GET
@Produces(MediaType.TEXT_PLAIN)
public List<PhoneNumber> getPhoneNumbers(@PathParam(value = "id") long id) {
    List<PhoneNumber> resultList = new ArrayList<>();
    EntityManager createEntityManager = emf.createEntityManager();
    String query="select p1 from PhoneNumber p1 where p1.person=:id";
    TypedQuery<PhoneNumber> createNamedQuery = createEntityManager.createQuery(query, PhoneNumber.class);
    createNamedQuery.setParameter("id", id);
    try {
        resultList = createNamedQuery.getResultList();
    } catch (Exception e) {
        System.out.println("Could not retrive phone list");
    }
    return resultList;
}

请你帮我一下,我做错了什么?

2 个答案:

答案 0 :(得分:0)

您需要使用person.id来查询:

String query="select p1 from PhoneNumber p1 where p1.person.id=:id";

或首先检索此人,然后将其用作参数:

Person person = createEntityManager.find(Person.class, id);

String query="select p1 from PhoneNumber p1 where p1.person=:id";
TypedQuery<PhoneNumber> createNamedQuery = createEntityManager.createQuery(query, PhoneNumber.class);
createNamedQuery.setParameter("id", person);

答案 1 :(得分:-1)

使用以下查询:

  select p1 from PhoneNumber p1 where p1.person.id=:id