Rule Definition
Using Hibernate API only brings several benefits:
- Performances: Hibernate provides potential for caching that is expected to outperforms queries that use direct JDBC access.
- Implementation: object mapping takes care of mapping the JDBC result sets to graph of persistent objects. Using direct JDBC API means writing the tedious code by hand to transform a JDBC ResultSet to an object graph.
- Database independence: the code can be used with all supported databases
- Transparent support of JDBC and JTA in both managed and non-managed environments
Remediation
If you really need to use SQL for feature that are not supported by Hibernate (like specifying SQL query hints or hierarchical queries such as Oracle CONNECT BY clause), you can use either SQL queries defined in the hibernate XML file or by using native SQL with org.hibernate.Session.createSQLQuery(java.lang.String queryString).
Violation Code Sample
List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
// VIOLATION
ResultSet rs = stmt.executeQuery("SELECT * FROM COMPANY");
while ( rs.next() ) {
EmployeeBean eb = new Employeebean();
eb.setName(rs.getString("name"));
eb.setSalary(rs.getFloat("salary"));
employeeList.add(eb);
}
Fixed Code Sample
Session session = sessionFactory.openSession();
Query query = session.createQuery("from EmployeeBean");
// FIXED
List<EmployeeBean> finalList = query.list();
Reference
Hibernate in Action (ISBN 1932394-15-X)
Related Technologies
JEE
Technical Criterion
Architecture - Multi-Layers and Data Access
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.