HibernateSessionFactory的用法

1-使用系统自带的HibernateSessionFactory类,该类是优秀的factory类。可以利用该类里的方法来完成我们一些需求

2-查询一条记录,查询多条记录

新建HibernateSessionFactory类。Myeclipse软件中,window-->openperpective-->myeclipsehibernate选择该方式显示窗口,就可以在相应的目录下新建HibernateSessionFactory类。

建立了HibernateSessionFactory类后就可以使用了。

查询一条记录

packagetest;

importorg.hibernate.Session;

importpo.Customer;

//向数据库查询一条记录

publicclassQueryt01{

publicstaticvoidmain(String[]args){

//使用框架提供的代码来获取session和关闭session,效率提高

Sessionsession=tool.HibernateSessionFactory.getSession();

//get方法获取

//找不到时返回空

Customercus=(Customer)session.get(Customer.class,"111");

System.out.println(cus.getAccount());

System.out.println(cus.getPassword());

System.out.println(cus.getCname());

System.out.println(cus.getBalance());

//关闭session

tool.HibernateSessionFactory.closeSession();

}

}

查询多条记录:也可以说是按条件查询

packagetest;

importorg.hibernate.Query;

importorg.hibernate.Session;

importpo.Customer;

//向数据库查询多条记录

publicclassQueryt02{

publicstaticvoidmain(String[]args){

//使用框架提供的代码来获取session和关闭session

Sessionsession=tool.HibernateSessionFactory.getSession();

//注意:Customer的位置不是填数据库的表名而是数据库表名映射的类名

Stringhql="fromCustomerwherebalance>=99";

Queryquery=session.createQuery(hql);

@SuppressWarnings("rawtypes")

java.util.Listlist=query.list();

for(inti=0;i<list.size();i++){

Customercus=(Customer)list.get(i);

System.out.println(cus.getAccount()+"======"+cus.getBalance());

}

tool.HibernateSessionFactory.closeSession();

}

}

packagetest;

importorg.hibernate.Session;

importorg.hibernate.Transaction;

importpo.Customer;

//向数据库修改一条记录,比较好的事物操作方法

publicclassSaveUpdate01{

publicstaticvoidmain(String[]args){

Sessionsession=tool.HibernateSessionFactory.getSession();

Customercus=newCustomer("111","111","111",99);

Transactiontras=session.beginTransaction();//事务提交

session.saveOrUpdate(cus);//数据库有该信息就覆盖,没有就添加

tras.commit();

tool.HibernateSessionFactory.closeSession();

}

}

packagetest;

importorg.hibernate.Session;

importorg.hibernate.Transaction;

importpo.Customer;

//向数据库修改一条记录,比较好的事物操作方法

publicclassUpdate01{

publicstaticvoidmain(String[]args){

Sessionsession=tool.HibernateSessionFactory.getSession();

Customercus=newCustomer();

session.load(cus,"111");

cus.setBalance(cus.getBalance()+1000000);

Transactiontras=session.beginTransaction();//事物提交

try{

session.update(cus);

tras.commit();

}catch(Exceptione){

tras.rollback();//回滚

}finally{

tool.HibernateSessionFactory.closeSession();

}

}

}

转载于:https://my.oschina.net/JiangTun/blog/324730

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值