VisualBuilder
  Home > Java > Tutorials > Using native SQL - Hibernate Tutorial
Tell a friend
Link to us
Total Members
      Members: 84661
     
Sitemap Forum Chat
Home
Hibernate Tutorial Home
1 . Introduction to Java Hibernate
2 . Introduction to Hibernate
3 . The Object/Relational Mapping Problem
4 . JDBC
5 . The Hibernate Alternative
6 . Hibernate Architecture and API
7 . Setting Up Hibernate
8 . Setting up Hibernate - Add the Hibernate libraries
9 . Registration Case Study
10 . Creating the Hibernate Configuration
11 . Writing the first Java File
12 . Writing the mapping file
13 . Writing the Business Component
14 . Writing the Test Client
15 . Managing Associations
16 . Finding by primary key
17 . Hibernate Query Language (HQL)
18 . Using native SQL
19 . Using Criteria Queries
20 . Using Ant to run the project
21 . Using Middlegen to generate source
22 . Review and the next steps
 
 
Java Home
Java Members (27650)
Java Member Articles ( 40 )
Java Discussion (275)
Java Q & A ( 174 )
- Java Ask Question
- Java Questions
- Java Unanswered Questions
Java Resources
Java Source Code (1096)
Java Articles (551)
Java Blogs (118)
Java Jobs (797)
Java Components (85)
Java Books (169)
Java Websites (127)
Java News (103)
 
GROUPS
.NET
ASP.NET
.NET
C#
ASP
Visual Basic
Java
Java
JSP
EJB
Other
Delphi
C++
Ajax
UML
JavaScript
PHP
Web Design
Web Hosting
SQL Server
Oracle
Project Management
More Groups

 
LEARNING CENTER
TUTORIALS
.NET
.NET Tutorial
ASP Tutorial
ASP.NET Database Tutorial
ASP.Net Security,Internationalisation And Deployment
ASP.NET Tutorial
C# Tutorial
Web Development
Flex Tutorial
HTML Tutorial
Learn AJAX Tutorial
PHP Tutorial
Software Development
Database Tutorial
SQL Tutorial
UML Tutorial
Java
Ant Tutorial
EJB 3 Tutorial
Hibernate Tutorial
Java Tutorial
Java Web Component Tutorial
Java XML Tutorial
JDBC Tutorial
JDK1.5 Tutorial
JSF Tutorial
JSP And J2EE Design Tutorial
JSP Tutorial
Spring Tutorial
Struts Tutorial

RESOURCES
Q & A (451 )
Source Code (3275 )
Articles (359 )
Books (372 )
Components (1596 )
News (892 )
Websites (1207 )

SUBMISSIONS
Submit Article
Submit Website
Submit News
Submit Source Code
Submit Component

COMMUNITY
Members Directory
Discussion Forum
Chat

SITE
About Us
Sitemap
Search
Contact Us
Link To Us
Feedback
Tell a Friend
Partners
Advertise

Java hibernate Tutorial
 Using native SQL
  << Prev: Hibernate Query Language (HQL) Next: Using Criteria Queries >>

In previous section,we learnt to use the Hibernate Query Language (HQL) that focused on the business entities instead of the vendor dependent syntax. This does not mean that we are bound to use the HQL throughout the Hibernate application if we want to perform some database operations. You may express a query in SQL,using createSQLQuery() and let Hibernate take care of the mapping from result sets to objects. Note that you may at any time call session.connection() and use the JDBC Connection directly. If you chose to use the Hibernate API,you must enclose SQL aliases in braces.


Let's see how to use the SQL queries by adding the functionality to find a user by user id using native SQL in our UserManager. Add the following method in UserManager class.


public User getUserById(long userId)
{
    org.hibernate.SQLQuery query = session.createSQLQuery(""
       "SELECT u.user_id as {u.userId},u.first_name as {u.firstName},u.last_name as {u.lastName},u.age as {u.age},u.email as {u.email} "
       "FROM USERS {u} WHERE  {u}.user_id=" userId "");
    query.addEntity("u",User.class);
    java.util.List l = query.list();
    java.util.Iterator users = l.iterator();
    User user = null;
    if(users.hasNext())

        user
= (User)users.next();
    return user;
}


In the above code,the result type is registered using query.addEntity("u",User.class) so that Hibernate knows how to translate the ResultSet obtained by executing the query. Also note that the aliases in the query are placed in braces and use the same prefix "u" as registered in query.addEntity(...). This way Hibernate knows  how to set attributes of the generated object. Also this way we can eliminate the confusion of attributes when more than one tables are used in query and both of them contain the same column name. query.list() actually executes the query and returns the ResulSet in the form of list of objects. We knew that this query is going to return only one object,so we returned only the first object if available.


Let's test this code by adding the following method in the TestClient.


public void testFindByNativeSQL(UserManager manager)
{
User user = manager.getUserById(2);
System.out.println("User found using native sql with ID=" user.getUserId() "\n"
"\tName=" user.getLastName() "\n"
"\tEmail=" user.getEmail()
"");
java.util.Iterator numbers = user.getPhoneNumbers().iterator();
while(numbers.hasNext()) {
PhoneNumber phone = (PhoneNumber)numbers.next();
System.out.println("\t\tNumber Type:" phone.getNumberType() "\n"
"\t\tPhone Number:" phone.getPhone());
}
}

Add the call to this method in main. To do this,add the following line in main.
client.testFindByNativeSQL(manager);


Be sure to pass a valid user id to this method that exists in the database with few valid phone numbers. This code will result in the following output.


User found using native sql with ID=2
Name=Elison
Email=john@visualbuilder.com
Number Type:Office
Phone Number:934757
Number Type:Home
Phone Number:934757

For more details on using native SQL in Hibernate,see Hibernate documentation.


  << Prev: Hibernate Query Language (HQL) Next: Using Criteria Queries >>
Java Hibernate Tutorial Home
Give feedback and win a prize.

 
   Printer Friendly
   Email to a friend
   Add to my Favourites    
  Download PDF version
   Report Bad Submissions
   Submit Feedback
 
  Delicious   Digg   Technorati   Blink   Furl   Reddit   Newsvine   Google Click each image to add
this page to each site.
 
 
Welcome Guest Signup
MEMBER'S PANEL
EMAIL
PASSWORD
Forgot your password?
New User? Click Here!
 
Resend Activation Email!
 
SEARCH
 
 
 
ADVERTISEMENT
Partner List
Code Project
ASP Alliance
More
 
 
 
 

Home | Login | About Us | Contact Us | Privacy Policy | Advertising