Hibernate存在的意义
与其他操作数据库的技术相比,Hibernate具有以下几点优势:
- Hibernate对JDBC访问数据库的代码做了轻量级封装,大大简化了数据访问层繁琐的重复性代码,并且减少了内存消耗,加快了运行效率。
- Hibernate是一个基于JDBC的主流持久化框架,是一个优秀的ORM实现,它很大程度的简化了DAO(数据访问对象)层的编码工作。
- Hibernate的性能非常好,映射的灵活性很出色,它支持很多关系型数据库,从一对一到多对多的各种复杂关系。
- 可扩展性强,由于源代码的开源以及API的开放,当本身功能不够用时,可以自行编码进行扩展。
创建映射代码
<?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>
<!-- 建立类与表的映射 -->
<class name="com.sssddd.hibernate.demo01.Customer" table="cst_customer">
<!-- 建立类中的属性和表中的主键对应 -->
<id name="cust_id" column="cust_id">
<generator class="native"/>
</id>
<!-- 建立类中的普通属性和表中的字段对应 -->
<property name="cust_name" column="cust_name" />
<property name="cust_source" column="cust_source" />
<property name="cust_industry" column="cust_industry" />
<property name="cust_level" column="cust_level" />
<property name="cust_phone" column="cust_phone" />
<property name="cust_mobile" column="cust_mobile" />
</class>
</hibernate-mapping>
创建一个Hibernate核心配置文件
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 配置hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--打印SQL语句 -->
<property name="hibernate.show_sql">true</property>
<!--格式化SQL语句 -->
<property name="hibernate.format_sql">true</property>
<mapping resouce="com/sssddd/hibernate/demo01/Customer.hbm.xml" />
</session-factory>
</hibernate-configuration>
程序测试代码
public class HibernateDemo01 {
@Test
public void demo01(){
//1.加载Hibernate的核心配置文件
Configuration configuration = new Configuration().configure();
//2.创建一个SessionFactory对象:类似于JDBC中连接池
SessionFactory sessionFactory = configuration.buildSessionFactory();
//3.通过SessionFactory获取到Session对象,类似于JDBC中Connection
Session session = sessionFactory.openSession();
//4.手动开启事务
Transaction transaction = session.beginTransaction();
//5.编写代码
// 添加一个名叫张三的对象
Customer customer = new Customer();
customer.setCust_name("张三");
session.save(customer);
//6、事务提交
transaction.commit();
//7.资源释放
session.close();
}
}
配置xml提示
windows->preferences->xml catalog->userspecfied entries->add
Hibernate的映射的配置
映射的配置
【class标签的配置】
标签用来建立类与表的映射关系
属性:
name :类的全路径
table :表名(类名与表名一致,table可以省略)
catalog :数据库名
【id标签的配置】
标签用来建立类中的属性与表中的主键的对应关系
属性:
name :类中的属性名
column :表中的字段名(类中的属性名和表中的字段名如果一致,column可以省略)
length :长度
type :类型
【property标签的配置】
标签用来建立类中的普通属性与表的字段的对应关系
属性:
name :类中的属性名
column :表中的字段名
length :长度
type :类型
not-null :设置非空
unique :设置唯一
Hibernate的核心的配置
Hibernate的核心配置方式(了解)
-
一种方式:属性文件的方式
hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver
…
hibernate.show_sql=true
属性文件的方式不能引入映射文件(手动编写代码加载映射文件) -
二种方式:XML文件的方式
hibernate.cfg.xml
核心的配置
必须的配置
连接数据库的基本的参数
驱动类
url路径
用户名
密码
方言
可选的配置
显示SQL :hibernate.show_sql
格式化SQL :hibernate.format_sql
自动建表 :hibernate.hbm2ddl.auto
none :不使用hibernate的自动建表
create :如果数据库中已经有表,删除原有表,重新创建,如果没有表,新建表。(测试)
create-drop :如果数据库中已经有表,删除原有表,执行操作,删除这个表。如果没有表,新建一个,使用完了删除该表。(测试)
update :如果数据库中有表,使用原有表,如果没有表,创建新表(更新表结构)
validate :如果没有表,不会创建表。只会使用数据库中原有的表。(校验映射和表结构)。
映射文件的引入
引入映射文件的位置
Hibernate的API
1.Configuration:Hibernate的配置对象
Configuration 类的作用是对Hibernate 进行配置,以及对它进行启动。在Hibernate 的启动过程中,Configuration 类的实例首先定位映射文档的位置,读取这些配置,然后创建一个SessionFactory对象。虽然Configuration 类在整个Hibernate 项目中只扮演着一个很小的角色,但它是启动hibernate 时所遇到的第一个对象。
作用:
加载核心配置文件
hibernate.properties
Configuration cfg = new Configuration();
hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
加载映射文件
// 手动加载映射
configuration.addResource(“com/itheima/hibernate/demo1/Customer.hbm.xml”);
2.SessionFactory:Session工厂
SessionFactory接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。
SessionFactory内部维护了Hibernate的连接池和Hibernate的二级缓存(不讲)。是线程安全的对象。一个项目创建一个对象即可。
-
配置连接池:(了解)
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!--在连接池中可用的数据库连接的最少数目 --> <property name="c3p0.min_size">5</property> <!--在连接池中所有数据库连接的最大数目 --> <property name="c3p0.max_size">20</property> <!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 --> <property name="c3p0.timeout">120</property> <!--每3000秒检查所有连接池中的空闲连接 以秒为单位--> <property name="c3p0.idle_test_period">3000</property>
-
抽取工具类
public class HibernateUtils { private static final Configuration cfg; private static final SessionFactory sf; static { cfg = new Configuration().configure(); sf = cfg.buildSessionFactory(); } public static Session openSession() { return sf.openSession(); } }
3.Session:类似Connection对象是连接对象
Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句)。但需要注意的是Session对象是非线程安全的。同时,Hibernate的session不同于JSP应用中的HttpSession。这里当使用session这个术语时,其实指的是Hibernate中的session,而以后会将HttpSession对象称为用户session。
Session代表的是Hibernate与数据库的链接对象。不是线程安全的。与数据库交互桥梁。
Session中的API
-
保存方法:
Serializable save(Object obj); -
查询方法:
T get(Class c,Serializable id);
T load(Class c,Serializable id);
get方法和load方法的区别?
1.get方法
采用的是立即加载,执行到这行代码的时候,就会马上发送SQL语句去查询。
查询后返回的是真是对象本身。
查询一个找不到的对象的时候,返回null。
2.load方法
采用的是延迟加载(lazy懒加载),执行到这行代码的时候,不会发送SQL语句,当真正使用这个对象的时候才会发送SQL语句。
查询后返回的是代理对象
查询一个找不到的对象的时候,返回ObjectNotFoundException异常//get方法 Customer customer = session.get(Customer.class,1001);//发送查询语句 System.out.println(customer); //load方法 Customer customer = session.load(Customer,1001); System.out.println(customer);
-
修改方法
/** * 修改方法 */ @Test public void updata() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); Customer customer = session.get(Customer.class, 1l); customer.setCust_name("李四"); session.update(customer); transaction.commit(); session.close(); }
-
删除方法
/** * 删除方法 */ @Test public void delete() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); Customer customer = session.get(Customer.class, 3l); session.delete(customer); transaction.commit(); session.close(); }
-
保存和更新
/** * 保存和更新 */ @Test public void save() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); Customer customer = new Customer(); //customer.setCust_id(11l); customer.setCust_name("大武当"); customer.setCust_industry("让国人");; session.saveOrUpdate(customer); transaction.commit(); session.close(); }
-
查询所有
/** * 查询所有 */ @Test public void query() { Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); //接收HQL:Hibernate Query Language 面向对象查询语言 //平常用 Query query = session.createQuery("from Customer"); List<Customer> list = query.list(); for (Customer customer : list) { System.out.println(customer); } //接收SQL,用于特别复杂的SQL语句时 SQLQuery query02 = session.createSQLQuery("select * fromcst_customer"); List<Object[]> list2 = query.list(); for (Object[] objects : list2) { System.out.println(Arrays.toString(objects)); } transaction.commit(); session.close(); }
Transaction:事务对象
Hibernate中管理事务的对象。
commit();//提交
rollback();//回滚