It's often needed to do a regular SQL query if Criteria or HQL query isn't flexible enough. This is achieved with Hibernate's org.hibernate.SessionFactory class function createSQLQuery. However query's list-method returns a List of objects inside of a List by default instead of List of domain instances. Luckily org.hibernate.SQLQuery class has a method named addEntity which can be used to map results to specific domain class.
Our domain class:
package fi.company.domain
class Product {
String name
int price
}
Service that uses sql
import org.hibernate.SessionFactory
import org.hibernate.Session
import org.hibernate.SQLQuery
class ProductSearchService {
SessionFactory sessionFactory
boolean transactional = false
List<Product> searchProducts(Map params) {
Session session = sessionFactory.getCurrentSession()
SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM product WHERE ...")
sqlQuery.addEntity(fi.company.domain.Product.class)
return sqlQuery.list()
}
}
Ei kommentteja:
Lähetä kommentti