類擬框架:Apache OJB,JDO,Toplink,EJB(CMP)JPA,IBatis
適合查詢及單個對象的編輯,適合于對象之間有清晰的關系,不適用于批量修改,關系復雜的對象及特定的sql功能
第一個項目
1 新建java項目
2 創建User Library,加入如下jar
* hibernate_home/hibernate3.jar
* hibernate_home/lib/*.jar
* MySql jdbc驗動
3 創建hibernate配置文件hibernate.cfg.xml,為了便于調試最好加入log4j配置文件
<hibernate-configuration>
<session-factory >
<!-- 連接串 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate1</property>
<!-- 驅動類 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 用戶名 -->
<property name="hibernate.connection.username">root</property>
<!-- 密碼 -->
<property name="hibernate.connection.password">root</property>
<!-- 適配器(反譯) -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<!-- 顯示sql語句 -->
<property name="hibernate.show_sql">true</property>
<!-- 可以防表被重新建立 -->
<property name="hibernate.hbm2ddl.auto">update</property>

<mapping resource="com/myobj/hibername/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4 定義實體類,繼承java.io.ser
5 定義User類的映射文件User.hbm.xml
<hibernate-mapping>
<class name="com.myobj.hibername.User" table="">
<id name="id">
<generator class="uuid"/>
<generator class="native"/>
<generator class="assigned"/>
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>
6 將User.hbm.xml文件加入到hibernate.cfg.xml文件中
<session-factory >
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate1</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/myobj/hibername/User.hbm.xml"/>
</session-factory>
7 編寫hbm2ddl工具類,將實體類生成數據庫表,手工建數據庫

public class ExportDB
{

public static void main(String[] args)
{
//讀取hibernate.cfg.xml文件,默認為.properties文件,
//讀取xml文件用new Configuration().configure()
Configuration cfg=new Configuration().configure();
//生成工具類
SchemaExport export=new SchemaExport(cfg);
//生成數據庫表
export.create(true, true);
}
}
8 開發客戶端Client類添加數據

public class Client
{


public static void main(String[] args)
{
//讀取hibernate.cfg.xml文件
Configuration cfg=new Configuration().configure();
//創建SessionFactory,與數據庫綁定,一個數據庫對應一個SessionFactory,與二級緩存相關,為重量級對象,是線程安全的
SessionFactory factory=cfg.buildSessionFactory();
//
Session session=null;//不同于connction,是對其的封裝,用時到連接池拿來conn

try
{
session = factory.openSession();
//開啟事務
session.beginTransaction();
User user = new User();
user.setName("張三");
user.setPassword("123");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
//保存數據
session.save(user);
//提交事務
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
//回滾事務
session.getTransaction().rollback();

}finally
{

if(session!=null)
{

if(session.isOpen())
{
//關閉session,是非線程安程的
session.close();
}
}
}
}
}
******session.update()相關類都改,session.merge()只改當前類,session.delete(),都要開啟事務******
9 為了方便跟蹤SQL執行,在hibernate.cfg.xml中加入
<property name="hibernate.show_sql">true</property>
持久化對象的狀態
1 瞬時對象:使用new操作符初始化的對象不是立刻就持久的。
2 持久化對象:持久實例是任何具有數據庫標識的實便函。
3 離線對象:Session關閉后持久化對象就變為離線對名象。
持久化對象的生命周期:

Transient對象new但在數據庫中沒有記錄且沒有被Session管理,
Persistent對象數據庫中有記錄,并Session在管理。在清理緩存(或臟數據檢查)時與數據庫同步。Session與一級緩存綁定.
Detached對象數據庫中有記錄,Session沒有管理它。
創建HibernateUtils類,對重量級容量進行優化:

public class HibernateUtils
{
private static SessionFactory factory;
//static塊只執行一次

static
{

try
{
Configuration cfg = new Configuration().configure();

} catch (Exception e)
{
e.printStackTrace();
}
}


public static SessionFactory getSessionFactory()
{
return factory;
}

public static Session getSession()
{
return factory.openSession();
}

public static void closeSession(Session session)
{

if(session!=null)
{

if(session.isOpen())
{
session.close();
}
}
}
}
Session接口的CRUD操作
瞬時/持久化/離線對象示例:

public class SessionTest extends TestCase
{

public void testSave1()
{
Session session=null;
Transaction tx=null;
User user=null;

try
{
session=HibernateUtils.getSession();
tx=session.beginTransaction();
//Transient狀態,未被Session管理
user=new User();
user.setName("ssssss");
user.setPassword("123");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
//persistent狀態,被Session管理,當屬性發生改變的時候,hibernate會自動和數據庫同步。
session.save(user);
user.setName("王五");
tx.commit();

}catch(Exception e)
{
e.printStackTrace();
tx.rollback();

}finally
{
HibernateUtils.closeSession(session);
}
//detached狀態,被Session踢出緩存,未被管理
user.setName("張三");

try
{
session = HibernateUtils.getSession();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}
}
Session接口
加載數據get與load的區別:
lazy代理:get沒有, load支持lazy;
查不存在數據:get返回null,load拋出異常ObjectNotFoundException
//get查詢數據

public void testReadByGetMethod1()
{
Session session=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
//采用get方式,馬上發出查詢sql,加載波User對象
User user=(User)session.get(User.class, "5c68c3ed206a327d01206a3281fa0001");
System.out.println(user.getName());
//persistent狀態,當屬性發生改變的時候,hibernate同自動和數據庫同步。
user.setName("大龍");
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}
//get查詢數據庫中不存在的數據

public void testReadByGetMethod2()
{
Session session=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
//采用get加載User對象,如果數據庫中不存在數據,返回null;
User user=(User)session.get(User.class, "5c68c");
System.out.println(user.getName());
//persistent狀態,當屬性發生改變的時候,hibernate同自動和數據庫同步。
user.setName("大龍");
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}
//load查詢數據

public void testReadByLoadMethod1()
{
Session session=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
//采用load加載User對象,不會發出查詢sql,因為load方法實現了lazy(懶加載或延遲加載)
//延遲加載:只有真正使用這個對象的時候,才加載(發出sql語句)
//hibernate延遲加載實現原理是代理方式,采用第三方組件添加User類的代理子類
User user=(User)session.load(User.class, "5c68c3ed206a327d01206a3281fa0001");//返回代理類
System.out.println(user.getName());
//persistent狀態,當屬性發生改變的時候,hibernate同自動和數據庫同步。
user.setName("龍哥");
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}
//load查詢數據庫中不存在的數據

public void testReadByLoadMethod2()
{
Session session=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
//采用load加載User對象,如果數據庫中不存在數據,
//拋出ObjectNotFoundException
User user=(User)session.load(User.class, "5c68c3e");//返回代理類
//如查不使用則沒有異常發生
System.out.println(user.getName());
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}

//手動構造detached狀態的對象
//一般修改時首加載再修改,不建議這樣作

public void testUpdate2()
{
Session session=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
//手動構造detached狀態的對象
User user=new User();
user.setId("5c68c3ed206a327d01206a3281fa0001");
user.setName("發哥");
session.update(user);
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}
//刪除對象

public void testDelete1()
{
Session session=null;
User user=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
user=(User)session.load(User.class, "5c68c3ed206a327d01206a3281fa0001");//返回代理類
session.delete(user);
session.getTransaction().commit();

} catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
//刪除扣user對象變為Transient狀態
}
Query接口初步

public void testQuery()
{
Session session=null;

try
{
session=HibernateUtils.getSession();
session.beginTransaction();
//通過session對象得到query對象實例
Query query=session.createQuery("from User");
//分頁
query.setFirstResult(2);
query.setMaxResults(2);
//得到User的集合
List<User>userList=query.list();

for(int i=0;i<userList.size();i++)
{
System.out.println(userList.get(i).getId());
System.out.println(userList.get(i).getName());
}
session.getTransaction().commit();

} catch (HibernateException e)
{
e.printStackTrace();
session.getTransaction().rollback();

}finally
{
HibernateUtils.closeSession(session);
}
}
posted on 2009-11-03 15:26
junly 閱讀(223)
評論(0) 編輯 收藏 所屬分類:
hibernate/orm