Hibernate单表操作

单表操作是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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值