8.2. Using native SQL Queries


Now that the result set is described, we are capable of executing the native SQL query. EntityManager provides all the needed APIs. The first method is to use a SQL resultset name to do the binding, the second one uses the entity default mapping (the column returned has to have the same names as the one used in the mapping). A third one (not yet supported by Hibernate entity manager), returns pure scalar results.
String sqlQuery = "select night.id nid, night.night_duration, night.night_date, area.id aid, "
    + "night.area_id, area.name from Night night, Area area where night.area_id = area.id "
    + "and night.night_duration >= ?";
Query q = entityManager.createNativeQuery(sqlQuery, "GetNightAndArea");
q.setParameter( 1, expectedDuration );
q.getResultList();
This native query returns nights and area based on the GetNightAndArea result set.
String sqlQuery = "select * from tbl_spaceship where owner = ?";
Query q = entityManager.createNativeQuery(sqlQuery, SpaceShip.class);
q.setParameter( 1, "Han" );
q.getResultList();
The second version is useful when your SQL query returns one entity reusing the same columns as the ones mapped in metadata.
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.