單表操作是Hibernate中的最簡單的操作了。因此簡單的說明一下。
首先編寫hibernate.cfg.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">user</property>
<property name="connection.url">db2...</property>
<property name="connection.password">pswd</property>
<property name="dialect">org.hibernate.dialect.DB2Dialect</property>
<property name="connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="bean/ZqTest.hbm.xml"/>
</session-factory>
</hibernate-configuration>
編寫bean(略) 和 對應的 hbm.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="bean.ZqTest" table="ZQTEST">
<id name="id" column="ID" type="int">
<generator class="increment"/>
</id>
<property name="name" column="NAME" type="string" not-null="true"/>
<property name="age" column="AGE" type="int" not-null="true"/>
</class>
</hibernate-mapping>
這就是一個最簡單的hibernate映射
以下是測試代碼
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = null;
tx = session.beginTransaction();
//創建一個新的實例
ZqTest z = new ZqTest();
z.setName("dd");
z.setAge(80);
//保存
//session.save(z);
//檢索
List testlist = session.createQuery("from ZqTest").list();
Iterator it = testlist.iterator();
//打印出查詢結果的個數
System.out.println("append:"+testlist.size());
//迭代出所有的查詢內容
while(it.hasNext())
{
ZqTest test = (ZqTest)it.next();
System.out.print("ID:" + test.getId());
System.out.print(" Name:" + test.getName());
System.out.println(" Age:" + test.getAge());
}
//檢索一個
ZqTest zz = (ZqTest)session.load(ZqTest.class,3);
System.out.print(zz.getName());
//更新 這裏直接將數據庫中的內容進行更新操作
zz.setName("ffff");
//session.saveOrUpdate(zz);
tx.commit();