Hibernate native queries in a file with no Entity

Viewed 144

My first choice where to put some @NamedNativeQueries is in the file where the data transfer object (a POJO, could be a record if I were using them) is defined. But the DTO isn’t an entity so Hibernate doesn't look at the file and the queries are not found. [If you are wondering, I use a @ConstructorResult in a @QueryResultSetMapping to create the objects.] I can put them in a different file with an @Entity but the semantics are wrong.

Is there any magic way to make Hibernate look at a file it otherwise would ignore?

1 Answers

You can add extra mapping resources to the session factory.

For example with Spring Boot:

spring.jpa.mapping-resources=hibernate/MyMapping.hbm.xml,hibernate/MyMapping2.hbm.xml

or without Spring Boot (from https://mkyong.com/hibernate/how-to-add-hibernate-xml-mapping-file-hbm-xml-programmatically/):

SessionFactory sessionFactory = new Configuration()
   .addResource("hibernate/MyMapping.hbm.xml")
   .buildSessionFactory();

Then in the added files (e.g. hibernate/MyMapping.hbm.xml) you can insert your named queries:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <sql-query name="test">
        select count(*) from SYSIBM.SYSDUMMY1
    </sql-query>
</hibernate-mapping>

Related