Hibernate框架-常用类及接口

Hibernate框架-常用类及接口

这篇文章简单介绍了hibernate核心的6个API

摘自度娘
Hibernate的API一共有6个,分别为:Session、SessionFactory、Transaction、Query、Criteria和Configuration。通过这些接口,可以对持久化对象进行存取、事务控制。

Configuration

主要是用于加载Hibernate的核心配置文件,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。

		//加载配置,调用空参构造configure() 空参加载方法:加载src目录下的hibernate.cfg.xml
		Configuration conf = new Configuration().configure();
		//也可以指定加载文件(手动加载,不建议),如加载src目录下的com.user包下的user.hbm.xml
		//Configuration conf = new Configuration().configure("user.hbm.xml");

SessionFactory接口

  • 负责初始化Hibernate。它充当数据存储源的代理,用于创建操作数据库核心对象session的工厂。简单来说功能就一个----创建session对象。
  • SessionFactory中有两种获取Session的方法,分别是openSession()和getCurrentSession(),openSession()表示获得全新的session(非线程安全),而getCurrentSession()指获得与线程绑定(线程安全)的session。
  • 注意:SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。所以可以在项目创建一个HibernateUtils工具类实现session的获取。工具类代码如下:
	public class HibernateUtils {

	private static SessionFactory sf;
	static {
		//保证只会被运行一次
		//1、加载配置,调用空参构造(空参加载方法configure():加载src目录下的hibernate.cfg.xml)
		Configuration conf = new Configuration().configure();
		
		//2、根据配置信息,创建SessionFactory对象
		sf=conf.buildSessionFactory();
	}
	
	//获得session=》获得全新session
	public static Session openSession() {

		Session session=sf.openSession();
		return session;		
	}
	
	//获得session=》获得与线程绑定的session
	public static Session getCurrentSession() {
		
		Session session=sf.getCurrentSession();
		return session;		
	}
}

Session接口

负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句)。但需要注意的是Session对象是非线程安全的。

Session常用的几个方法

save():保存对象
update ():修改操作
delete():删除
get()/load():根据主键进行查询(get为立即加载,load为延迟加载[在执行时不发送任何SQL语句,而是返回一个对象,直到使用该对象时才执行查询)
avenOrUpdate():执行save或update操作
createQuery():获取一个Query对象,执行HQL语句时用到
CreateSQLQUery():获取一个可以操作SQL的SQLQuery对象,执行原生SQL语句时用到
createCriteria():取一个Criteria对象,它可以完成条件查询,执行无语句查询(Criteria查询)时会用到

Transaction 接口

Transaction 接口是对实际事务实现的一个抽象,这些实现包括JDBC的事务、JTA 中的UserTransaction、甚至可以是CORBA 事务。主要用于管理事务,它是Hibernate的事务接口,对底层的事务进行了封装。使用它可以进行事务操作,如事务回滚rollback(),事务提交commit()

Query接口

让你方便地对数据库及持久对象进行查询,它可以有两种表达方式:HQL语言或本地数据库的SQL语句(SQLQuery是Query的子类。)。Query经常被用来绑定查询参数、限制查询记录数量,并最终执行查询操作。

Criteria接口

与Query接口非常类似,允许创建并执行面向对象的标准化查询。值得注意的是Criteria接口也是轻量级的,它不能在Session之外使用。

最后结合上面6个常用类及接口,用一个例子整合一下

@Test
	//条件查询
	public void fun20() {
		//加载配置文件
		Configuration cfg = new Configuration().configure();
		//创建SessionFactory对象
		SessionFactory sf = cfg.buildSessionFactory();
		//获得session
		Session session = sf.openSession();
		//开始事务
		Transaction tx = session.beginTransaction();
		//执行操作(查询Customer中cust_id为3的对象)
		//-------------------SQLQuery(为Query的子类)--------------------------
		
		//1、原生SQL语句(别混淆,这里要写数据库表名)
		String sql = "select * from customer2 where cust_id=3";
		SQLQuery query1 = session.createSQLQuery(sql);
		//指定将结果集封装到对象(addEntity(?.class))
		query1.addEntity(Customer.class);
		
		Customer c1 = (Customer) query1.uniqueResult();
		System.out.println("原生SQL语句查询结果:"+c1);
		
		//--------------------Query ----------------------
		//HQL语句
		
		String sql2 = "from Customer where cust_id=3";
		//2、根据SQL语句创建查询对象
		Query query2 = session.createQuery(sql2);
		//3、根据查询对象获得查询结果,有两种方法,返回多个用list(),返回一个用uniqueResult()
		Customer c2 = (Customer) query2.uniqueResult();

		System.out.println("HQL语句查询结果:"+c2);
		
		//---------------------Criteria------------------------
		//Criteria查询
		Criteria criteria = session.createCriteria(Customer.class);
		//添加查询参数
		criteria.add(Restrictions.eq("cust_id", 3));
		Customer c3 = (Customer) criteria.uniqueResult();
		System.out.println("Criteria查询结果:"+c3);
		//-----------------------------------------------------
		//提交事务,关闭资源
		tx.commit();
		session.close();
		sf.close();
		
	}

运行结果:

九月 19, 2018 3:18:40 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Hibernate: 
    select
        * 
    from
        customer2 
    where
        cust_id=3
原生SQL语句查询结果:Customer [cust_id=3, cust_name=360卫士, cust_source=null, cust_level=null, cust_phone=null]
九月 19, 2018 3:18:42 下午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_,
        customer0_.cust_name as cust_nam2_0_,
        customer0_.cust_source as cust_sou3_0_,
        customer0_.cust_level as cust_lev4_0_,
        customer0_.cust_phone as cust_pho5_0_ 
    from
        customer2 customer0_ 
    where
        customer0_.cust_id=3
HQL语句查询结果:Customer [cust_id=3, cust_name=360卫士, cust_source=null, cust_level=null, cust_phone=null]
Hibernate: 
    select
        this_.cust_id as cust_id1_0_0_,
        this_.cust_name as cust_nam2_0_0_,
        this_.cust_source as cust_sou3_0_0_,
        this_.cust_level as cust_lev4_0_0_,
        this_.cust_phone as cust_pho5_0_0_ 
    from
        customer2 this_ 
    where
        this_.cust_id=?
Criteria查询结果:Customer [cust_id=3, cust_name=360卫士, cust_source=null, cust_level=null, cust_phone=null]
九月 19, 2018 3:18:43 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql:///customer]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值