一、Hibernate常用的类与接口。
各层次的介绍。
1. hibernate.cfg.xml
是hibernate的核心配置文件,配置内容包括:数据库的用户名,密码,url,数据库的类型(及方言),连接池等等。配置对象关系文件的位置。
演示代码:
<!--?xml version=
1.0
encoding=UTF-
8
?-->
<!-- hibernate的核心配置文件 -->
<hibernate-configuration>
<session-factory>
<!--配置使用的driver -->
<property name=
"connection.driver_class"
>com.mysql.jdbc.Driver</property>
<property name=
"connection.username"
>root</property>
<property name=
"connection.password"
>xu827928</property>
<property name=
"connection.url"
>jdbc:mysql:
//127.0.0.1:3306/hbmtest</property>
<!-- 配置dialect方言,明确告诉hibernate连接的是哪种数据库 -->
<property name=
"dialect"
>org.hibernate.dialect.MySQLDialect</property>
<!-- 显示出对应sql语句 -->
<property name=
"show_sql"
>
true
</property>
<!-- 格式化输出sql语句 -->
<property name=
"format_sql"
>
true
</property>
<!--让hibernate帮我们创建 一张表 -->
<!--
update:如果没有表则创建表 如果有表 则看表结构是否变化 如果有变化则会创建新表
如果没有则添加
create:每次都创建新的数据库
-->
<!-- <property name=hbm2ddl.auto>create</property> -->
<property name=
"hbm2ddl.auto"
>update</property>
<!-- 指定管理对象映射文件 -->
<mapping resource=
"com/xh/domain/Employee.hbm.xml"
></mapping>
</session-factory>
</hibernate-configuration>
2.*.hbm.xml
该文件为对象关系映射文件,一个pojo类的属性与一张数据库表的字段一一对应。配置了类与类的对应关系(one-to-one,one-to-
many,many-to-one,
代码:
<!--?xml version=
1.0
encoding=UTF-
8
?-->
<!-- 这是映射Employee表的hibernate -->
<!-- 该文件用于配置domain对象和表的映射关系 -->
<hibernate-mapping
package
=
"com.lc.domain"
>
<
class
name=
"Employee"
table=
"employee"
>
<!-- id元素用于指定主键属性 -->
<id column=
"id"
name=
"id"
type=
"java.lang.Integer"
>
<generator
class
=
"increment"
>
</generator></id>
<!-- 对其他属性的配置 -->
<property name=
"name"
type=
"java.lang.String"
>
<column name=
"name"
not-
null
=
"false"
>
</column></property>
<property name=
"email"
type=
"java.lang.String"
>
<column name=
"email"
not-
null
=
"false"
>
</column></property>
<property name=
"hiredate"
type=
"java.util.Date"
>
<column name=
"hiredate"
not-
null
=
"false"
>
</column></property>
</
class
>
</hibernate-mapping>
3. Configuration是hibernate的核心配置类,用来管理hibernate.cfg.xml和*.hbm.xml文件。读取hibernate.cfg.xml文件,加载
数据库驱动,用户名,密码,连接池。
代码:
Configuration cfg=new Configuration().configure();
4. SessionFactory
SessionFactory是一个重量级的类。通常一个数据库连接只创建一个SessionFactory对象。这个类由Configuration创建。通过它可以
创建Session实例。
代码:
Configuration cfg=new Configuration().configure();
SessionFactory sessionFactory= cfg.buildSessionFactory();
Session session=sessionFactory.getCurrentSession();
//Session session=sessionFactory.openSession();
5.Session
Session一个实例代表与数据库的一次操作(当然一次操作可以是crud组合),由SessionFactory创建。Session是线程不同步的(不安全),
因此要保证在同一线程中使用,可以用getCurrentSessiong()。
因此要保证在同一线程中使用,可以用getCurrentSessiong()。
代码:
Configuration cf=
new
Configuration().configure();
SessionFactory sf=cf.buildSessionFactory();
Session s=sf.getCurrentSession();
//或者是: Session s=sf.openSession();
Session常用的几个方法(通过id操作)
a.保存一个对象(记录)—save方法
b.删除一个对象(记录)—delete方法
c.查询一个对象(记录)—get/load方法
d.修改一个对象(记录)—update方法
6.Query
Query接口类型的对象可以对数据库操作,它可以使用Hql,Qbc,Qbe和原生SQL(native Sql)对数据库操作.官方推荐使用Hql语句。Query接口
和Criteria接口非常相似。