lishman levelup
«previous  next»


Getting Started
Associations
HQL



Reading and Writing with Hibernate


We have an entity class mapped to the COUNTRY table and a Hibernate Session object to communicate with our database, so let's put Hibernate to work.

The COUNTRY table includes this data:
CTRY_ID CTRY_NAME AREA
27 Ukraine 233000
28 pain 95365
29 Columbia 440831
224 Yugoslavia 98766

Read

To return a single object for a given identifier, use either of these methods:
Country spain = (Country) session.load(Country.class, 28);

Country spain = (Country) session.get(Country.class, 28);
Both of the methods generate this SQL (or something very similar):
select
  CTRY_ID,
  CTRY_NAME,
  AREA
from
  COUNTRY
where
  CTRY_ID=?
The difference between the two methods is that load() will throw a HibernateException if the row does not exist whereas get() will return a null value.

Create

To persist an object to the database, use the save() method.
session.beginTransaction();

Country croatia = new Country();
croatia.setName("Croatia");
croatia.setArea(21831);
int croatiaId = (Integer) session.save(croatia);

session.getTransaction().commit();
This SQL is generated when used with an Oracle database:
select hibernate_sequence.nextval from dual

insert into COUNTRY (CTRY_NAME, AREA, CTRY_ID) values (?, ?, ?)
The @GeneratedValue annotation on the Country entity ensures that a sequential value is generated for the CTRY_ID column. This value is then returned by the save() method.

A transaction is started on the Session object and can be committed, using commit(), or rolled back, using rollback(), as you would expect.

Update

To update values on a persistent object, simply retrieve the entity, make the required changes to the field values and commit the transaction. There is no explicit update method to be called.
session.beginTransaction();

Country spain = (Country) session.load(Country.class, 28);
spain.setName("Spain");     // Fix capital 'S'
spain.setArea(195365);      // and correct the area

session.getTransaction().commit();
This SQL is executed when the transaction is committed:
 
update COUNTRY set CTRY_NAME=?, AREA=? where CTRY_ID=?
 

Delete

To permanently remove a persistent object, use the delete() method inside a transaction.
session.beginTransaction();

Country yugoslavia = (Country) session.load(Country.class, 224);
session.delete(yugoslavia);

session.getTransaction().commit();
The delete() method generates this SQL:
 
delete from COUNTRY where CTRY_ID=?
 

Quick Start contains a complete working set of all the SQL and Java code featured in this section.
»