gamelan
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
New
 
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




Nominate the Best Products or Technologies for Developer.com Product of the Year!




Developer Jobs

Be a Commerce Partner














 


Developer News -
Microsoft Shows Some Ankle With Visual Studio    September 29, 2008
Gentoo Linux Cancels Distribution    September 26, 2008
It's Official: Windows 7 at PDC, WinHEC    September 25, 2008
Oracle Keeps Building on Spoils From BEA    September 24, 2008
Free Tech Newsletter -

An Introduction to Object-Relational Mapping with Hibernate
By Olexiy & Alexander Prokhorenko

Go to page: Prev  1  2  3  

Finding and Loading Product Objects

Searching for and loading existing objects is a very simple task for Hibernate. With the use of its query language, we very easily can take an object (or set of objects) by its ID, a name, or other properties. We also can take either the whole object or its certain properties separately. Let's consider the FindProductByName class:

import java.util.List;
import net.sf.hibernate.Hibernate;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import Product;

// Usage:
//  java FindProductByName <title>
public class FindProductByName {
   public static void main(String[] args) throws Exception {
      String query = "SELECT product " +
                     "FROM product IN CLASS test.hibernate.Product " +
                     "WHERE product.name=:name";

      String name = args[0];

      Configuration cfg = new Configuration().addClass(Product.class);
      SessionFactory sf = cfg.buildSessionFactory();
      Session sess = sf.openSession();

      List list = sess.find(query, name, Hibernate.STRING);

      if (list.size() == 0) {
         System.out.println("Product [" + name + "] not found!");
      System.exit(0);
      }

      Product p = (Product) list.get(0);
      sess.close();
      System.out.println("Found product: " + p);
   }
}

Let's consider the most interesting places of the above-mentioned code:

In the code, there is a query with a WHERE expression. All is very similar to the usual SQL format.

Initialize Hibernate as we did in the first example. This time, we already have created files of a configuration and mapping (XML file). The sess.find() method carries out the query and establishes the name of a product given to it, as an argument for the search with the Hibernate.STRING type.

As a result, we will get an object of the java.util.List class, filled with Product objects from a database that satisfies the search conditions.

With the Product p = (Product) list.get (0); expression, we take the first found object.

Updating and Removing Products

By now, you already should have a decent understanding of how Hibernate works. Therefore, now we will make our examples hardly less in size, having cleaned out all repeating and unimportant items.

Following is the example of how to increase all Products' prices by 10% in one transaction. We should write the following:

...
double percentage = Double.parseDouble(args[0])/100;
sess = sf.openSession();
Transaction t = sess.beginTransaction();
Iterator iter = list.iterator();
while (iter.hasNext()) {
       Product p = (Product) iter.next();
       p.setPrice(p.getPrice() * (1 + percentage));
       sess.saveOrUpdate(p);
}
t.commit();
sess.close();
...

And, at last, for removal of a Product, we should cause a method sess.delete(product). Please, do not overlook also carrying out commit() at the end of transaction to confirm changes if only certainly the option autocommit in your database is turned on.

Afterword

This article shows what kind of tool is Hibernate, and also shows a few advantages. From it you have learned how simple is to keep any kind of Java objects, and then to manipulate them. Opportunities for Hibernate are incomparably wider. I also just need to mention that Hibernate arms the developer with very a powerful object-oriented query language, HQL, which has a set of various useful features.

Go to page: Prev  1  2  3  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Data & Java Archives








JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES