Is this possible to map a SQL Native query (instead of a table) with an Entity without annotations (using XML configuration)??
I know that i can make a View in the database and map this view as a workaround to this, but I try to avoid this solution because the Schema is automatically generated from the Entities model, and I would have to create the view manually afterwards.
I know also that with annotations there exist something like @SqlResultSetMapping, but I am not allowed to use annotations.
A view is the proper way. If you want to somehow store an SQL query in the database, and refer to its results regularly (as if it were a table), then that is precisely the description of a view.
So just create a view and map it.
If that does not solve your problem, please edit your answer to explain why a solution using a view is not practical. Maybe we can help you then.
For mapping legacy tables on an entity using Hibernate you could use a DAO method like this one:
public List<Audit> getAudits(Integer branchId, Integer locationId, Date fromDate, Date toDate, int first, int count, String sortProperty, boolean ascending) {
// columns renamed to match sort properties and hibernate mapping
StringBuilder query = new StringBuilder(
"SELECT AUD_Number AS number,"
+ " AUD_Number_REL AS relationNumber,"
+ " AUD_Name_REL AS relationName,"
+ " AUD_Date AS date,"
+ " FROM audit WHERE 1");
if (branchId!= null) {
query.append(String.format(" AND AUD_Number_BRN = %s", branchId));
}
if (locationId!= null) {
query.append(String.format(" AND AUD_Nummer_LOC = %s", locationId));
}
if (fromDate != null) {
query.append(String.format(" AND AUD_Date >= %s", DateConverter.dateToSql(fromDate)));
}
if (toDate != null) {
query.append(String.format(" AND AUD_Date <= %s", DateConverter.dateToSql(toDate)));
}
query.append(String.format(" ORDER BY %s %s", sortProperty, ascending ? "ASC" : "DESC"));
query.append(String.format(" LIMIT %s, %s", first, count));
return (List<Audit>) getSession().createSQLQuery(query.toString()).addEntity(Audit.class).list();
}
Meanwhile in mappings.hbm.xml:
<class name="Audit">
<id name="number" type="integer" />
<property name="relationNumber" type="integer" />
<property name="relationName" type="string" />
<property name="date" type="datetime" />
</class>
etc...
Omitting spring context for brevity.
Does this help?
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.