Hibernate Native SQL Mapping to Entity with Select

2019-02-21 00:09发布

问题:

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.

回答1:

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