Hibernate – Native SQL
Hibernate by means of a Native SQL facility, can directly interact with the database like MySQL, Oracle, etc., and all the database-specific queries can be executed via this facility. This feature is much useful if the application is an old application and running for a long time. All of a sudden we cannot bring back new changes but instead with Native SQL facilities, we can work on that. Mainly to support older applications, we can go for Hibernate – Native SQL
We are going to see a maven-driven project. Hence as a first step, let us see pom.xml that specifies all the dependencies, properties, etc.
Important files for the project
Hibernate properties are specified here.
Let us see the POJO class now
So above listed files are connecting medium. Let’s see the MySQL table as well
Let us assume that we have some set of records in that
Now, let us see the way of writing queries to communicate with MySQL and get the details
We can get all the details because of the Complete Row facility
// Query the database by means of specific tablename straightaway. // SQL should be like how we do from SQLCommandline or workbench String studentsQuery = "select * from studentsdetails"; // New instance of Query for the given SQL SQLQuery sqlQuery1 = session.createSQLQuery(studentsQuery);
If each row is converted into an object of the POJO class, we can use addEntity() method of SQLQuery
In case we want to partially select a few columns alone means, it is possible by means of addScalar(). Hibernate internally uses ResultSetMetaData. We need to specify the data type when we are using addScalar()
Finally, let us see how to update the data
Checking the DB data as well:
The Complete Code
The main advantage of hibernate is totally not applicable because of this NativeSQL approach, but still, it helps in the age-old applications that are running in production and available for live means we can go for this approach. Sometimes in terms of support, we can go for NativeSQL, but newly developed applications or the applications that are planned to support multi-database supportive should not go with this approach.