1.hibernate是什么?
- hibernate 是一个框架(framework)
- hibernate 是一个orm框架
- o rm (object relation mapping) 对象关系映射 框架
- o object -> 业务层(只对对象操作)
- r relation-> 关系数据库
- m mapping 对象关系映射文件
- hibernate 处于我们项目的持久层位置(正因为如此,所以有人又把hibernate称为 持久层框架)
- hibernate 实际上就是对jdbc进行了轻量级的封装.
- JDBC(Java DataBase Connectivity,java数据库连接):是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。
- hibernate 的基础还是我 们java 反射机制
把对象持久化: 把对象的信息保存到数据库或者是文件.
总结: hibernate 是对jdbc进行轻量级封装的 orm 框架,充当项目的持久层.
快如入门案例:
hiberante 可以用在 j2se 项目,也可以用在 j2ee (web项目中)
struts是web框架,所以用在 web项目
我们使用手动配置hibernate方式开发一个hibernate 项目,完成crud操作 。
开发流程
- 创建一个项目
- 画出一个简单项目框架示意图
- 引入hibernate 开发包 (从网上下载 google hibernate http://www.hibernate.org),完后我们
- 开发hibernate 有三种方法(开发顺序)
我们使用第二种开发项目
创建employe 表以及employee的domain对象
create table employee(
id number primary key,
name varchar2(64) not null,
email varchar2(64) not null,
hiredate date not null)
package com.domain;
import java.util.Date;
public class Employee {
//成员变量的名字最好与数据库中表的字段相同
private int id;
private String name;
private String email;
private java.util.Date hiredata;
private double salary;
private String pwd;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public java.util.Date getHiredata() {
return hiredata;
}
public void setHiredata(java.util.Date hiredata) {
this.hiredata = hiredata;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
开发domain对象和对象关系映射文件
对象关系映射文件: 作用是用于指定 domain对象和表的映射关系. ,该文件的取名有规范:
domain对象.hbm.xml,一般我们放在 和domain对象同一个文件夹下(包下)
我们的Employee.hbml.xml配置文件 :
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.hsp.domain">
<class name="Employee" table="employee">
<!-- id元素用于指定主键属性 -->
<id name="id" column="id" type="java.lang.Integer">
<!-- 该元素用于指定主键值生成策略hilo native increment sequence uuid -->
<generator class="sequence">
<param name="sequence">emp_seq</param>
</generator>
</id>
<!-- 对其它属性还有配置 -->
<property name="name" type="java.lang.String">
<column name="name" not-null="false" />
</property>
<property name="email" type="java.lang.String" >
<column name="email" not-null="false"/>
</property>
<property name="hiredate" type="java.util.Date">
<column name="hiredate" not-null="false" />
</property>
</class>
</hibernate-mapping>
手动配置我们的hibernate.cfg.xml文件
该文件用于配置 连接的数据库的类型,driver,,用户名,密码 ,url ....同时管理 对象关系映射文件 ,该文件的名称,我们一般不修改.
hibernate.cfg.xml配置文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- hibernate 设计者,给我们提供了一写常用的配置 -->
<!-- 配置使用的driver -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- MySQL连接端口号(3306)与数据库(user) -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/user</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">admin</property>
<!-- dialect翻译为方言 Hibernate根据你选择的“方言”,针对每种数据库,作调整,如生成不同的SQL语句等 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 显示出对于sql的格式化 -->
<property name="show_sql">true</property>
<!-- 指定管理的对象映射文件 -->
<mapping resource="com/domain/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
测试文件TestMain.java
package com.test;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.*;
import com.domain.Employee;
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1.创建Configuration,读取配置文件
Configuration cf=new Configuration().configure("hibernate.cfg.xml");
//2.创建SessionFactory,会话工厂
SessionFactory sf=cf.buildSessionFactory();
//创建会话session(与数据库交互)
Session session=sf.openSession();
//要求用事物提交
Transaction transaction =session.beginTransaction();
/*Employee emp=new Employee();
emp.setId(2);
emp.setName("樊梦真");
emp.setEmail("dafeijuFMZ@qq.com");
emp.setHiredata(new Date());
session.save(emp);*/
String hql="from Employee";
Query query=session.createQuery(hql);
List<Employee> list=query.list();
for(int i=0;i<list.size();i++) {
Employee emp=(Employee)list.get(i);
System.out.println(emp.getId()+" "+emp.getPwd()+" ");
}
transaction.commit();
session.close();
}
}
在SSH中用spring接管hibernate.cfg.xml
先前定义映射关系的Employee.hbm.xml文件还是保留。但是配置数据源的文件可以在applicationContext中接管。下面是spring中的applicationContext的配置文件
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="testService" class="com.test.TestService">
<property name="name" value="Jack"></property>
</bean>
<!-- 事务管理器->SessionFactory->数据源->数据库 -->
<!-- 配置数据源 (关联数据库)-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/user"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="30"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1"/>
</bean>
<!-- 配置会话工厂(关联数据源) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 接管了hibernate对象映射文件 -->
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.generate_statistics=true
</value>
</property>
</bean>
</beans>
可以看到在配置文件中配置了会化工厂sessionFactory接管。所以在具体的使用时,就不用再去创建Configuiration去读取,也无需再声明新的sessionFactory。
package com.test;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.Employee;
public class TestHibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
SessionFactory sf=(SessionFactory) ac.getBean("sessionFactory");
Session s=sf.openSession();
Transaction transaction =s.beginTransaction();
String hql="from Employee";
Query query=s.createQuery(hql);
List<Employee> list=query.list();
for(int i=0;i<list.size();i++) {
Employee emp=(Employee)list.get(i);
System.out.println(emp.getId()+" "+emp.getPwd()+" ");
}
transaction.commit();
s.close();
}
}
补充:在使用hbm查询时的用法(SSH)
public Employee chechEmployee(Employee emp) {
// TODO Auto-generated method stub
String hql="FROM Employee WHERE id=? AND pwd=?";
Session s=sessionFactory.openSession();
Transaction transaction =s.beginTransaction();
List<Employee>empList = s.createQuery(hql).setString(0, emp.getId()+"").setString(1, emp.getPwd()).list();
transaction.commit();
s.close();
if(empList.size()==1) {
return empList.get(0);
}else {
return null;
}
}