Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.
import java.util.*;
import org.hibernate.*; import org.hibernate.criterion.*;
public class SimpleRetrieveTest {
public static void main(String[] args) { HibernateUtil.setup("create table EVENTS ( uid int, name VARCHAR, start_Date date, duration int, location_id int);"); HibernateUtil.setup("create table locations ( uid int, name VARCHAR, address VARCHAR);"); // hibernate code start Session session = HibernateUtil.currentSession(); Transaction tx = session.beginTransaction();
Location location = new Location(); location.setName("USA"); location.setAddress("Address"); session.save(location);
Event e= new Event(); e.setId(11111L); e.setName("testSave"); e.setStartDate(new Date()); e.setLocation(location);
session.save(e);
Criteria crit = session.createCriteria(Event.class); crit.add( Expression.eq( "name", "testSave" ) ); crit.setMaxResults(1); List results = crit.list();
System.out.println(results.size());
tx.commit(); HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
// hibernate code end } }
///////////////////////////////////////////////////////////////////////// <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping > <class name="Location" table="locations" lazy="true"> <id name="id" column="uid" type="long"> <generator class="native"/> </id> <property name="name" type="string"/> <property name="address" type="string"/> </class> </hibernate-mapping>
/////////////////////////////////////////////////////////////////////////
public class Location {
private Long id; private String name; private String address;
publi
Specify custom SQL INSERT (and UPDATE) statements using <sql-insert> and <sql-update> in Hibernate3, or using a custom persister in Hibernate 2.1.
You will also need to write a UserType to perform binding to/from the PreparedStatement.
A Great Tutorials Portal
Aquarian Infotech System
Copyright © 2008 interviewmaterial.com. All rights reserved.