This article mainly introduces the Hibernate framework, the concept of ORM and the introduction of hibernate. I believe you will use hibernate after reading it.
If you want speed, you will not reach it. If you want speed, you will reach it!
1, Basic concepts
hibernate is an ORM framework, which is called object "relative database mapping. It establishes some mapping between java objects and relational databases to realize direct access to java objects.
2, Why use hibernate?
Since hibernate is about the relationship between java objects and relational databases, it is the DAO layer of data persistence layer in MVC.
First, let's review the experience of writing DAO layer:
- Operate XML in DAO layer, encapsulate data to XML file, read and write XML file data to realize CRUD.
- In DAO layer, native JDBC is used to connect database to realize CRUD.
- We dislike that JDBC's connection, statement, resultset and other objects are too cumbersome. We use the encapsulation component of native JDBC -- > dbutils component
Let's take a look at the code of the program after using DbUtils:
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); } } }
In fact, when using DbUtils, the coding in DAO layer is very regular.
- When inserting data, java bean objects are split and assembled into SQL statements
- When querying data, use SQL to combine columns in database tables and assemble them into Java Bean objects
There is a mapping relationship between Javabean objects and columns in database tables! If the program can automatically generate SQL, hibernate came into being.
3, Getting started with hibernate
Learning a framework is nothing more than three steps:
- Introduction of jar package
- Configuration XML file
- Familiarity with API
1. Introducing jar package
We're using hibernate 5.4
hibernate5.jar core + required (6) + jpa directory + database driver package
2. Configuration XML file
(1) Write an Entity object - > employee.java
Write the object map - > employee.hbm.xml. Generally, it is placed in the same directory as JavaBean objects
Modify on the above template ~ this configuration file will be explained in detail below!
<?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) Main configuration file 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"> <!-- Import resource file --> <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/> <!-- To configure c3p0 data source --> <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> <!-- Definition Hibernate Of SessionFactory LocalSessionFactoryBean--> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- Depending on the injection data source, inject the above defined dataSource --> <property name="dataSource" ref="dataSource"/> <!-- mappingResouces Property to list all mapped files --> <property name="mappingResources"> <list> <!-- The following are used to list Hibernate Mapping file --> <value>com/ssh/entities/Department.hbm.xml</value> <value>com/ssh/entities/Employee.hbm.xml</value> <value>hibernate.cfg.xml</value> </list> </property> <!-- Definition Hibernate Of SessionFactory Attribute --> <property name="hibernateProperties"> <props> <!-- Specify database dialect --> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect</prop> <!-- Whether to automatically create the database every time as required --> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- display Hibernate Generated by persistent operation SQL --> <prop key="hibernate.show_sql">true</prop> <!-- take SQL The script is formatted and then output --> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <!-- To configure spring Declarative transactions for 1.To configure hibernate Transaction manager for --> <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.Configure transaction properties <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> --> <!-- 3.Configure transaction pointcuts, and then associate transaction properties with transaction pointcuts --> <!-- <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"> <!-- Define new interceptor stack, configure prepare Interceptor stack's alwaysInvokePrepare The parameter value is false--> <interceptors> <interceptor-stack name="sshStack"> <interceptor-ref name="paramsPrepareParamsStack"> <param name="prepare.alwaysInvokePrepare">false</param> </interceptor-ref> </interceptor-stack> </interceptors> <!-- Using the new interceptor stack--> <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>
3. Class file
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("Are you sure you want to delete"+lastName+"Information?"); 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("Delete successful!"); $tr.remove(); }else{ alert("Delete failed!"); } }); } return false; }) }) </script> </head> <body> <h4>Employee List Page</h4> <s:if test="#request.employees == null||#request.employees.size() == 0"> //No employee information </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, Complete hibernate add, delete, modify and query
5, configuration
1. Configuration management class: a class that mainly manages configuration files
It has a subclass annotation configuration, which means that we can use annotations instead of XML configuration files to configure corresponding information.
2, method
(1) The configure method is used to load the configuration file:
- If a parameter is specified, the path profile of the parameter is loaded
- If no parameter is specified, hibernate.cfg.xml under src / directory will be loaded by default
(2) buildSessionFactory() is used to create a session factory
(3) sessionFactory method
Session factory -- > the factory of session, which also represents the file hibernate.cfg.xml... Hibernate.cfg.xml has a node like < session factory >
(4) openSession method, create a session object
(5) getCurrentSession method to create or retrieve the session object
3,session
Session is the most important object of hibernate. Session maintains a connection. As long as you use hibernate to operate the database, you need to use session object.
update operation
Using the save method, call this method to save the object in the database. The session object provides other methods to update the database
- session.save(obj); save an object
- session.update(obj); [update an object]
- session.saveOrUpdate(obj); [how to save or update]
- No primary key is set, execute save;
- Set primary key to perform update operation;
- If there is no error in setting the primary key!
6, HQL query
1. HQL: hibernate query language is the object-oriented query language provided by hibernate
The object and its properties are queried, case sensitive
2, SQL:strut query language. Case insensitive
3. Local SQL query
Sometimes, if SQL is very complex, and we can't rely on SQL query to achieve functions, we need to use native SQL for complex query, but it has a defect and can't cross platform, so we have configured the "dialect" of the database in the main configuration file.
//Encapsulate all records as User objects and store them in the List collection SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM user").addEntity(User.class); List list = sqlQuery.list(); System.out.println(list);
6, beginTransaction method
When a transaction is opened, a transaction object is returned. hibernate stipulates that all databases must be executed in the transaction environment, otherwise an error will be reported!
Database 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>
Other parameter configuration
<!-- Definition Hibernate Of SessionFactory Attribute --> <property name="hibernateProperties"> <props> <!-- Specify database dialect --> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect</prop> <!-- Whether to automatically create the database every time as required --> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- display Hibernate Generated by persistent operation SQL --> <prop key="hibernate.show_sql">true</prop> <!-- take SQL The script is formatted and then output --> <prop key="hibernate.format_sql">true</prop> </props> </property>
Load mapping file
<property name="mappingResources"> <list> <!-- The following are used to list Hibernate Mapping file --> <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 execution flow chart
Java video and SSH integration in Silicon Valley
SSH project source code:
Link: https://pan.baidu.com/s/1BK0V1wxA-GQrWco10WEzeg extraction code: 2e3e
Recommended blog
Java framework (SSH, SSM, Springboot)