一.ORM概念
1.简介
O, Object 对象
R, Realtion 关系 (关系型数据库: MySQL, Oracle…)
M,Mapping 映射
ORM:对象关系映射。
2.ORM解决的具体问题
1)存储: 把对象的数据直接保存到数据库
2)获取: 直接从数据库拿到一个对象
3.Hibernate与ORM的关系
Hibernate是ORM的实现
二.使用Hibernate写一个案列
1.搭建一个Hibernate环境,开发步骤
1) 下载源码
版本:hibernate-distribution-3.6.0.Final
2) 引入jar文件
hibernate3.jar核心 + required 必须引入的(6个) + jpa 目录 + 数据库驱动包
3) 写对象以及对象的映射
Employee.java 对象
Employee.hbm.xml 对象的映射 (映射文件)
4) src/hibernate.cfg.xml 主配置文件
- 数据库连接配置
- 加载所用的映射(*.hbm.xml)
5) App.java 测试
2.编写javaBean
public class Employee
{
private int empId;
private String empName;
private Date workDate;
public int getEmpId()
{
return empId;
}
public void setEmpId(int empId)
{
this.empId = empId;
}
public String getEmpName()
{
return empName;
}
public void setEmpName(String empName)
{
this.empName = empName;
}
public Date getWorkDate()
{
return workDate;
}
public void setWorkDate(Date workDate)
{
this.workDate = workDate;
}
public String toString()
{
return "Employee [empId=" + empId + ", empName=" + empName
+ ", workDate=" + workDate + "]";
}
}
3.编写对象映射文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="包名">
//name是对象的名字,table对应的是数据库中表的名字
<class name="Employee" table="employee">
<!-- 主键 ,映射-->
<id name="empId" column="id">
<generator class="native"/>
</id>
<!-- 非主键,映射 -->
<property name="empName" column="empName"></property>
<property name="workDate" column="workDate"></property>
</class>
</hibernate-mapping>
4.编写数据库主配置文件
<!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:///hib_demo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="映射文件的名字"/>
</session-factory>
</hibernate-configuration>
5.编写Junit测试类
public class Test
{
@Test
public void testHello() throws Exception {
Employee emp = new Employee();
emp.setEmpName("经理");
emp.setWorkDate(new Date());
Configuration config = new Configuration();
config.configure();
SessionFactory sf = config.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(emp);
tx.commit();
session.close();
sf.close();
}
}
三.Hibernate Api简单介绍
1)Configuration:配置管理类对象
config.configure():加载主配置文件的方法(hibernate.cfg.xml)默认加载src/hibernate.cfg.xml;
config.configure(“cn/config/hibernate.cfg.xml”); 加载指定路径下指定名称的主配置文件;
config.buildSessionFactory(); 创建session的工厂对象
2)SessionFactory session的工厂(或者说代表了这个hibernate.cfg.xml配置文件)
sf.openSession():创建一个sesison对象
sf.getCurrentSession():创建session或取出session对象
3)Session:session对象维护了一个连接(Connection), 代表了与数据库连接的会话。 Hibernate最重要的对象: 只用使用hibernate与数据库操作,都用到这个对象
session.beginTransaction(); 开启一个事务; hibernate要求所有的与数据库的操作必须有事务的环境,否则报错!
更新:
session.save(obj); 保存一个对象
session.update(emp); 更新一个对象
session.saveOrUpdate(emp); 保存或者更新的方法:
没有设置主键,执行保存;
有设置主键,执行更新操作;
如果设置主键不存在报错!
主键查询:
session.get(Employee.class, 1); 主键查询
session.load(Employee.class, 1); 主键查询 (支持懒加载)
3.1)HQL查询
HQL查询与SQL查询区别:
a.SQL: (结构化查询语句)查询的是表以及字段; 不区分大小写。
b.HQL: hibernate query language 即hibernate提供的面向对象的查询语言
c.查询的是对象以及对象的属性。
d.区分大小写。
3.2).Criteria查询:完全面向对象的查询
本地SQL查询:复杂的查询,就要使用原生态的sql查询,也可以,就是本地sql查询的支持!(缺点: 不能跨数据库平台!)
4)Transaction:hibernate事务对象
四.Hibernate CRUD
1.接口层代码案例
public interface IEmployeeDao
{
void save(Employee emp);
void update(Employee emp);
Employee findById(Serializable id);
List<Employee> getAll();
List<Employee> getAll(String employeeName);
List<Employee> getAll(int index, int count);
void delete(Serializable id);
}
2.代码实现接口
public class EmployeeDaoImpl implements IEmployeeDao
{
public Employee findById(Serializable id)
{
Session session = null;
Transaction tx = null;
try {
// 获取Session
session = HibernateUtils.getSession();
// 开启事务
tx = session.beginTransaction();
// 主键查询
return (Employee) session.get(Employee.class, id);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
public List<Employee> getAll()
{
Session session = null;
Transaction tx = null;
try {
session = HibernateUtils.getSession();
tx = session.beginTransaction();
// HQL查询
Query q = session.createQuery("from Employee");
return q.list();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
public List<Employee> getAll(String employeeName)
{
Session session = null;
Transaction tx = null;
try
{
session = HibernateUtils.getSession();
tx = session.beginTransaction();
Query q =session.createQuery("from Employee where empName=?");
q.setParameter(0, employeeName);
return q.list();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
public List<Employee> getAll(int index, int count)
{
Session session = null;
Transaction tx = null;
try
{
session = HibernateUtils.getSession();
tx = session.beginTransaction();
Query q = session.createQuery("from Employee");
q.setFirstResult(index); // 查询的其实行
q.setMaxResults(count); // 查询返回的行数
List<Employee> list = q.list();
return list;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
public void save(Employee emp)
{
Session session = null;
Transaction tx = null;
try
{
session = HibernateUtils.getSession();
tx = session.beginTransaction();
session.save(emp);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
public void update(Employee emp)
{
Session session = null;
Transaction tx = null;
try
{
session = HibernateUtils.getSession();
tx = session.beginTransaction();
session.update(emp);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
public void delete(Serializable id)
{
Session session = null;
Transaction tx = null;
try
{
session = HibernateUtils.getSession();
tx = session.beginTransaction();
Object obj = session.get(Employee.class, id);
if (obj != null)
{
session.delete(obj);
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
tx.commit();
session.close();
}
}
}