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?
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 (eg 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.