1.Hibernate是什么?
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了轻量级的封装, 它将POJO(实体类)与数据库表简历映射关系,是一个全自动的ORM框架,Hibernate可以自动生成sql语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库.
2.对象关系映射(ORM)?
原生的JDBC关注的是:针对表操作的sql语句
ORM关注的是操作的对象
3.Hibernate是纯粹的ORM框架
优点:所有数据库的操作全是基于面向对象的,使面向对象的编程思路保持统一
缺点:对于复杂的SQL语句的转换的操作会降低
4.Hibernate通过什么方式来位置ORM?
a.数据库表
b.实体类
c.关系映射文件(xx.hbm.xml)目的是用来描述表和实体类之间的对应关系
d.核心配置文件(hibernate.cfg.xml)目的使用来描述数据库环境的(类似:DBhelper)
e.Hibernate提供的一组操作数据的Api
5.Hibernate的开发步骤:
a.在官网下载开发包(http://hibernate.org/orm/)
b.导入jar报到项目
c.创建数据表
d.编写实体类
e.编写关系映射文件(实体类名.hbm.xml)一般放在和实体类共同级目录下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- 描述包名 --> <hibernate-mapping package="com.svse.bean"> <!-- 描述实体类和对应的表 name:实体类名 table:数据库中的表名--> <class name="CustomerBean" table="customers"> <!-- 描述主键 name:实体类中作为主键的属性名 column:数据库中表中作为主键的字段--> <id name="id" column="id"> <!-- 主键生成策略 native自动匹配策略--> <generator class="native"/> </id> <!-- 描述普通属性 name:实体类中普通属性名 column:column:数据库中表中对应实体类中的属性的字段--> <property name="address" type="string" column="address"/> <property name="customer_code" type="string" column="customer_code"/> <property name="customer_name" type="string" column="customer_name"/> <property name="other" type="string" column="other"/> <property name="phone" type="string" column="phone" not-null="false"/> <property name="relation" type="string" column="relation" not-null="false"/>
</class> </hibernate-mapping> |
6.编写核心配置文件(hibernate.cfg.xml)放在src目录下(classpath目录)
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings --> <!-- 数据库驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 连接字符串 --> <property name="connection.url">jdbc:mysql://localhost:3306/customer_db</property> <!-- 数据库用户名 --> <property name="connection.username">root</property> <!-- 数据库密码 --> <property name="connection.password">root</property> <!-- 数据库方言,用来描述使用的是什么数据库 --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!--显示生成的sql语句 --> <property name="show_sql">true</property> <!-- 是否自动生产数据表 ,有4个可选值--> <!-- create:表示启动的时候先drop,再create create-drop: 也表示创建,只不过再系统关闭前执行一下drop update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新 validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异搜索常,并不做更新 --> <property name="hbm2ddl.auto">update</property>
<!-- 说明实体类的映射文件的路径 --> <mapping resource="com/svse/bean/CustomerBean.hbm.xml"/>
</session-factory>
</hibernate-configuration> |
7.使用Hibernate提供的API进行操作
session.save(); session.delete(); session.get(); session.update(); |