views:

41

answers:

2

If I have something like this

@Entity
public class Facility {
    ...
    @ManyToOne
    @JoinColumn(name="CUSTOMER_FK")
    private Customer customer;
    ...
}

does my @NameQuery like this

@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.customer=:customer_fk")

or like this

@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.CUSTOMER_FK=:customer_fk")
+1  A: 

In JPQL you use the names of the properties, not the database columns. So - the first option.

But when you pass parameters, you pass the whole objects, not their IDs. In your case, you either pass a Customer instance, or make the where clause look for c.customer.id (and you'd better name the alias f, not c)

Bozho
when I try to do this `@NamedQuery(name="Facility.findByCustomerId", query="select c from Facility c where c.customer = '1'")`. I got nothing return back. Did I do something wrong?
Harry Pham
@Harry Pham see my update
Bozho
+4  A: 

You need to stop thinking foreign keys and to start thinking object when using JPQL. Let's take a closer look:

select c from Facility c where c.CUSTOMER_FK=:customer_fk

Does your Facility have a CUSTOMER_FK property? No, so the above query is incorrect. Next one:

select c from Facility c where c.customer=:customer_fk

Syntacticly, this one is correct. But you're still not thinking object. Here, the query expect you to pass an instance of customer, not a FK. I'd thus rewrite it like this (it is the same query but it communicates IMO the intention much better and I'd actually avoid any foo_fk convention, you don't really manipulate FK with JPA):

select c from Facility c where c.customer = :customer

And if you really want to find by id, you should navigate through the association and write:

select c from Facility c where c.customer.id = :id
Pascal Thivent
much better understand after seeing your post. TYVM
Harry Pham
@Harry You're welcome, glad it was helpful.
Pascal Thivent
I hope it ok if I ask another question. if I do this `select c from Facility c where c.customer.id = '1'"`. Then I got what I want. But if I do this `select c from Facility c where c.customer.id = :id`, then in my Enterprise Bean. I do `Query query.setParameter("id", "1")` then I get nothing. Any idea why?
Harry Pham
@Harry What is the type of `id`?
Pascal Thivent
type `Long`. I try to convert `Long.parseLong("1")`, but still no go
Harry Pham
@Harry Using `query.setParameter("id", 1L)` doesn't work?
Pascal Thivent
Yeah it work. And I try this and it work as well, `query.setParameter("id", new Long("1"))`. Thanks a lot man :)
Harry Pham