hibernatenative-sql

Hibernate Native SQL Mapping to Entity with Selection Example


I tried to create native sql query and map to entity class with parameter but fail.

/**
     * @return
     */
    public List<PoolRuleMapping> getAllPRM() {
        Session session = null;
        List<PoolRuleMapping> prmList = null;

        try {
            session = HibernateSessionFactory.getSession();

            Query q = session.createSQLQuery("select * from pool_rule_mapping").addEntity(PoolRuleMapping.class);
            prmList = q.list();

        } catch (HibernateException e) {
        } finally {
            session.close();
        }

        return prmList;
    }

Please provide an example. Thanks.


Solution

  • You can try the below code.

    session.createSQLQuery("select * from pool_rule_mapping")
     .addScalar("ID", Hibernate.LONG)
     .addScalar("NAME", Hibernate.STRING)
     .addScalar("SOMEDATE", Hibernate.DATE)
     .addEntity(PoolRuleMapping.class);
    

    Also, you can try specifying alias for individual fields.

    select prm.id AS ID, prm.name AS NAME, prm.somedate as SOMEDATE from pool_rule_mapping prm