本文主要講解hibernate框架,ORM的概念和hibernate入門,相信你們看了以後就會使用hibernate了。javascript
欲速則不達,欲達則欲速!html
1、基本概念java
hibernate是一種ORM框架,全稱爲Object_Relative Database-Mapping,在java對象與關係數據庫之間創建某種映射,以實現直接存取java對象。jquery
2、爲何要使用hibernate?spring
既然hibernate是關於java對象和關係數據庫之間的聯繫的話,也就是咱們MVC中的數據持久層DAO層。sql
首先,先來回顧一下編寫DAO層的的經歷:數據庫
咱們來看看使用DbUtils以後,程序的代碼是怎麼樣的:express
public class CategoryDAOImpl implements zhongfucheng.dao.CategoryDao{ @Override publicvoidaddCategory(Category category) { QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource()); String sql = "INSERT INTO category (id, name, description) VALUES(?,?,?)"; try { queryRunner.update(sql, new Object[]{category.getId(), category.getName(), category.getDescription()}); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public Category findCategory(String id) { QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource()); String sql = "SELECT * FROM category WHERE id=?"; try { Category category = (Category) queryRunner.query(sql, id, new BeanHandler(Category.class)); return category; } catch (SQLException e) { throw new RuntimeException(e); } } @Override public List<Category> getAllCategory() { QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource()); String sql = "SELECT * FROM category"; try { List<Category> categories = (List<Category>) queryRunner.query(sql, new BeanListHandler(Category.class)); return categories; } catch (SQLException e) { throw new RuntimeException(e); } } }
其實使用DbUtils時,DAO層中的代碼編寫是頗有規律的。apache
Javabean對象和數據庫表中的列存在映射關係!若是程序可以自動生成SQL就行了,hibernate應運而生。session
3、hibernate快速入門
學習一個框架無非就是三步:
一、引入jar包
咱們使用的是Hibernate5.4的版本
hibernate5.jar核心 + required 必須引入的(6個) + jpa 目錄 + 數據庫驅動包
二、配置XML文件
(1)編寫一個Entity對象->Employee.java
編寫對象映射->Employee.hbm.xml。通常它和JavaBean對象放在同一目錄下
在上面的模板上修改~下面會具體講解這個配置文件!
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2020??1??9?? ????9:08:43 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="com.ssh.entities.Employee" table="SSH_EMPLOYEE"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="native" /> </id> <property name="lastName" type="java.lang.String"> <column name="LASTNAME" /> </property> <property name="email" type="java.lang.String"> <column name="EMAIL" /> </property> <property name="birth" type="java.util.Date"> <column name="BIRTH" /> </property> <property name="createTime" type="java.util.Date"> <column name="CREATE_TIME" /> </property> <many-to-one name="department" class="com.ssh.entities.Department"> <column name="DEPARTMENT_ID" /> </many-to-one> </class> </hibernate-mapping>
(2)主配置文件hibernate.cfg.xml
<?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.dialect">org.hibernate.dialect.OracleDialect</property> <property name="hibernate.connection.driverClass">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.username">mine</property> <property name="hibernate.connection.password">mine</property> <property name="hibernate.connection.jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="com/ssh/entities/Department.hbm.xml"/> <mapping resource="com/ssh/entities/Employee.hbm.xml"/> </session-factory> </hibernate-configuration>
applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop" 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 導入資源文件 --> <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/> <!-- 配置c3p0數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 定義Hibernate的SessionFactory LocalSessionFactoryBean--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 依賴注入數據源,注入上面定義的dataSource --> <property name="dataSource" ref="dataSource"/> <!-- mappingResouces屬性用來列出所有映射文件 --> <property name="mappingResources"> <list> <!-- 如下用來列出Hibernate映射文件 --> <value>com/ssh/entities/Department.hbm.xml</value> <value>com/ssh/entities/Employee.hbm.xml</value> <value>hibernate.cfg.xml</value> </list> </property> <!-- 定義Hibernate的SessionFactory的屬性 --> <property name="hibernateProperties"> <props> <!-- 指定數據庫方言 --> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect</prop> <!-- 是否根據須要每次自動建立數據庫 --> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 顯示Hibernate持久化操做所生成的SQL --> <prop key="hibernate.show_sql">true</prop> <!-- 將SQL腳本進行格式化後再輸出 --> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <!-- 配置spring的聲明式事務 1.配置hibernate的事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"></bean> 2.配置事務屬性 <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> --> <!-- 3.配置事務切入點,再把事務屬性和事務切入點關聯起來 --> <!-- <aop:config> <aop:pointcut expression="execution(* com.guor.ssh.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="exAdvice" pointcut-ref="txPointcut"/> </aop:config> --> </beans>
applicationContext-beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="employeeDao" class="com.ssh.dao.EmployeeDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="departmentDao" class="com.ssh.dao.DepartmentDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="employeeService" class="com.ssh.service.EmployeeService"> <property name="employeeDao" ref="employeeDao"></property> </bean> <bean id="departmentService" class="com.ssh.service.DepartmentService"> <property name="departmentDao" ref="departmentDao"></property> </bean> <bean id="employeeAction" class="com.ssh.actions.EmployeeAction" scope="prototype"> <property name="employeeService" ref="employeeService"></property> <property name="departmentService" ref="departmentService"></property> </bean> </beans>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <!-- 定義新的攔截器棧, 配置prepare攔截器棧的alwaysInvokePrepare參數值爲false--> <interceptors> <interceptor-stack name="sshStack"> <interceptor-ref name="paramsPrepareParamsStack"> <param name="prepare.alwaysInvokePrepare">false</param> </interceptor-ref> </interceptor-stack> </interceptors> <!-- 使用新的攔截器棧--> <default-interceptor-ref name="sshStack"></default-interceptor-ref> <action name="emp-*" class="employeeAction" method="{1}"> <result name="list">/WEB-INF/views/emp-list.jsp</result> <result type="stream" name="delete"> <param name="contentType">text/html</param> <param name="inputName">inputStream</param> </result> <result name="input">/WEB-INF/views/emp-input.jsp</result> <result name="success" type="redirect">/emp-list</result> </action> </package> </struts>
三、類文件
EmployeeAction
package com.ssh.actions; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Map; import org.apache.struts2.interceptor.RequestAware; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; import com.ssh.entities.Employee; import com.ssh.service.DepartmentService; import com.ssh.service.EmployeeService; public class EmployeeAction extends ActionSupport implements RequestAware, ModelDriven<Employee>,Preparable{ private static final long serialVersionUID = 1L; private EmployeeService employeeService; public void setEmployeeService(EmployeeService employeeService) { this.employeeService = employeeService; } private DepartmentService departmentService; public void setDepartmentService(DepartmentService departmentService) { this.departmentService = departmentService; } public String list() { request.put("employees",employeeService.getAll()); return "list"; } private Integer id; public void setId(Integer id) { this.id = id; } public InputStream inputStream; public InputStream getInputStream() { return inputStream; } public String delete() { try { employeeService.delete(id); inputStream = new ByteArrayInputStream("1".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return SUCCESS; } public String input() { request.put("departments", departmentService.getAll()); return INPUT; } public void prepareInput() { if(id!=null) { model = employeeService.get(id); } } public String save() { if(id == null) { model.setCreateTime(new Date()); } employeeService.saveOrUpdate(model); System.out.println("model"); return SUCCESS; } public void prepareSave() { if(id == null) { model = new Employee(); }else { model = employeeService.get(id); } } private Map<String,Object> request; @Override public void setRequest(Map<String, Object> arg0) { this.request = arg0; } @Override public void prepare() throws Exception {} private Employee model; @Override public Employee getModel() { return model; } }
EmployeeService
package com.ssh.service; import java.util.List; import com.ssh.dao.EmployeeDao; import com.ssh.entities.Employee; public class EmployeeService { private EmployeeDao employeeDao; public void setEmployeeDao(EmployeeDao employeeDao) { this.employeeDao = employeeDao; } public void saveOrUpdate(Employee employee) { employeeDao.saveOrUpdate(employee); } public void delete(Integer id) { employeeDao.delete(id); } public List<Employee> getAll(){ List<Employee> employees = employeeDao.getAll(); return employees; } public Employee get(Integer id) { return employeeDao.get(id); } }
EmployeeDao
package com.ssh.dao; import java.util.List; import com.ssh.entities.Employee; public class EmployeeDao extends BaseDao{ public void delete(Integer id) { String hql = "DELETE From Employee e where e.id=?0"; getSession().createQuery(hql).setParameter(0,id).executeUpdate(); } public List<Employee> getAll() { //String hql = "From Employee e LEFT OUTER JOIN FETCH e.department"; String hql = "From Employee"; return getSession().createQuery(hql).list(); } public void saveOrUpdate(Employee employee) { getSession().saveOrUpdate(employee); } public Employee get(Integer id) { return (Employee)getSession().get(Employee.class,id); } }
emp-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src = "js/jquery-2.1.4.min.js"></script> <script type="text/javascript"> $(function(){ $(".delete").click(function(){ var lastName = $(this).next(":input").val(); var flag = confirm("肯定要刪除"+lastName+"的信息嗎?"); if(flag){ var $tr = $(this).parent().parent(); var url = this.href; var args = {"time":new Date()} $.post(url,args,function(data){ if(data=="1"){ alert("刪除成功!"); $tr.remove(); }else{ alert("刪除失敗!"); } }); } return false; }) }) </script> </head> <body> <h4>Employee List Page</h4> <s:if test="#request.employees == null||#request.employees.size() == 0"> 沒有任何員工信息 </s:if> <s:else> <table border="1" cellpadding="10" cellspacing="0"> <tr> <td>ID</td> <td>LASTNAME</td> <td>EMAIL</td> <td>BIRTH</td> <td>CREATETIME</td> <td>delete</td> <td>edit</td> </tr> <s:iterator value="#request.employees"> <tr> <td>${id }</td> <td>${lastName }</td> <td>${email }</td> <td>${birth }</td> <td>${createTime }</td> <td> <a href="emp-delete?id=${id } " class="delete">Delete</a> <input type="hidden" value="${lastName }"/> </td> <td><a href="emp-input?id=${id }">Edit</a></td> </tr> </s:iterator> </table> </s:else> </body> </html>
emp-input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h4>Employee Input Page</h4> <s:form action="emp-save" method="post"> <s:if test="id != null"> <s:textfield name="lastName" label="LastName" disabled="true"></s:textfield> <s:hidden name="id"></s:hidden> </s:if> <s:else> <s:textfield name="lastName" label="LastName"></s:textfield> </s:else> <s:textfield name="email" label="Email"></s:textfield> <s:textfield name="birth" label="Birth"></s:textfield> <s:select list="#request.departments" listKey="id" listValue="departmentName" name="department.id" label="Department"> </s:select> <s:submit></s:submit> </s:form> </body> </html>
4、完成hibernate增刪改查
5、configuration
一、配置管理類:主要管理配置文件的一個類
它擁有一個子類annotationConfiguration,也就是說咱們可使用註解來代替XML配置文件來配置相對應的信息。
二、方法
(1)configure方法用於加載配置文件:
(2)buildSessionFactory()用於建立session工廠
(3)sessionFactory方法
SessionFactory-->Session的工廠,也能夠說表明了hibernate.cfg.xml這個文件...hibernate.cfg.xml的就有<session-factory>
這麼一個節點
(4)openSession方法,建立一個session對象
(5)getCurrentSession方法,建立session對象或取出session對象
三、session
session是hibernate最重要的對象,session維護了一個鏈接(connection),只要使用hibernate操做數據庫,都須要使用session對象。
更新操做
使用save方法,調用這個方法把對象保存在數據庫中,session對象提供其餘方法進行對數據庫的更新
6、HQL查詢
一、HQL:hibernate query language即hibernate提供的面向對象的查詢語言
查詢的是對象以及對象的屬性,區分大小寫
二、SQL:strut query language結構化查詢語言。不區分大小寫
三、本地SQL查詢
有的時候,若是SQL是很是複雜的,咱們不能靠SQL查詢來實現功能的話,咱們就須要使用原生的SQL進行復雜查詢,可是它有一個缺陷,不能跨平臺,所以咱們在主配置文件中已經配置了數據庫的「方言」了。
//將全部的記錄封裝成User對象存進List集合中 SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM user").addEntity(User.class); List list = sqlQuery.list(); System.out.println(list);
6、beginTransaction方法
開啓事務,返回的是一個事務對象,hibernate規定全部的數據庫都必須在事務環境下進行,否者報錯!
數據庫配置
<session-factory> <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property> <property name="hibernate.connection.driverClass">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.username">mine</property> <property name="hibernate.connection.password">mine</property> <property name="hibernate.connection.jdbcUrl">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="com/ssh/entities/Department.hbm.xml"/> <mapping resource="com/ssh/entities/Employee.hbm.xml"/> </session-factory>
其它參數配置
<!-- 定義Hibernate的SessionFactory的屬性 --> <property name="hibernateProperties"> <props> <!-- 指定數據庫方言 --> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect</prop> <!-- 是否根據須要每次自動建立數據庫 --> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 顯示Hibernate持久化操做所生成的SQL --> <prop key="hibernate.show_sql">true</prop> <!-- 將SQL腳本進行格式化後再輸出 --> <prop key="hibernate.format_sql">true</prop> </props> </property>
加載映射文件
<property name="mappingResources"> <list> <!-- 如下用來列出Hibernate映射文件 --> <value>com/ssh/entities/Department.hbm.xml</value> <value>com/ssh/entities/Employee.hbm.xml</value> <value>hibernate.cfg.xml</value> </list> </property>
7、hibernate執行流程圖
SSH項目源碼:
連接: https://pan.baidu.com/s/1BK0V1wxA-GQrWco10WEzeg 提取碼: 2e3e
推薦博客