如何使用HQL查询索引集合中的元素?

时间:2016-06-03 03:47:32

标签: java hibernate hql

数据库数据:

pkmn_id | pkmn_name

1 |火龙

这些是我的实体:

Pokemon.Class

@Entity
@Table(name = "pkmn")
@Inheritance(strategy = InheritanceType.JOINED)
@NamedQuery(name = "@GET_POKEMON_BY_ID", query = "SELECT pkmn FROM Pokemon as pkmn FireType as ft WHERE pkmn.pkmnID = pkmn.fireAttributes[0]")
public abstract class Pokemon {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "pkmn_id")
    private int pkmnID;

    @Column(name = "pkmn_name")
    private String pkmnName;

    public long[] fireAttributes = { 1, 2, 3, 4, 5 };

FireType.class

@Entity
@Table(name = "pkmn_firetype")
@DynamicUpdate(value = true)
@SelectBeforeUpdate(value = true)
public class FireType extends Pokemon {

    @Column(name = "fire_immunity")
    private int fireImmunity;

    @Column(name = "fire_attack")
    private int fireAttack;

PokemonServlet.class

SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Query query2 = session.getNamedQuery("@GET_POKEMON_BY_ID");
        FireType pk2 = (FireType) query2.uniqueResult();
        System.out.println(pk2.getFireAttack());

        session.getTransaction().commit();
        session.close();

我的NamedQuery中有一个错误,问题在于我如何在WHERE子句中使用数组索引。我对在WHERE子句中包含索引集合的正确方法感到困惑。

实现此查询的正确方法是什么,其中pkmn_id必须与数组索引中的值匹配才能检索正确的对象?

这是我的参考 JBoss Hibernate Documentation

1 个答案:

答案 0 :(得分:0)

你忘了只用逗号。您的查询应如下所示,并在您将ID与多个ID进行比较时使用。

SELECT pkmn FROM Pokemon as pkmn , FireType as ft WHERE pkmn.pkmnID in pkmn.fireAttributes[0]