Michael Ouyang
Michael Ouyang

Reputation: 1827

JPA createQuery()

When using JPA createQuery(), I found that we can use both class name and entity name to get the DB data.

This is by class name

em.createQuery("from com.model.Stuff s", Stuff.class).getResultList();

And this is from entity name

em.createQuery("from Stuff s", Stuff.class).getResultList();

This is in orm.xml

<entity class="com.model.Stuff" name="Stuff">

No matter which one i use, JPA can get the specific class that i am using from the orm.xml or from the annotation that i put in class.

  1. So why i have to put Stuff.class in the parameter?

  2. Because it can only put at most two parameters in createQuery(), What if i have to select two Class to do some join?

    i cannot do this

    em.createQuery("from Stuff s, Thing t where s.id = t.stuff_id", Stuff.class, Thing.class).getResultList();

  3. Is

    em.createQuery("from Stuff s", Stuff.class).getResultList();

    equal

    em.createQuery("select s from Stuff s", Stuff.class).getResultList();

Thanks to give me some help.

Upvotes: 1

Views: 856

Answers (1)

f.khantsis
f.khantsis

Reputation: 3540

  1. Stuff.class goes into the parameter to determine what type of query result object. A query can be infinitely complicated with dozens of nested types, but it must return one type of object in the end.

  2. Then you must create a third Java type that will be result of join. Think about it, what type SHOULD the result be after a join?

  3. As far as I know, yes

Upvotes: 2

Related Questions