1、首先在maven中添加jar包依賴
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
2、創建resources文件夾並設置為資源文件夾

3、在resources文件夾中創建hibernate配置文件,兩種方法
(1)、直接創建hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/dss</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<!-- 可以將向數據庫發送的SQL語句顯示出來 -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化SQL語句 -->
<property name="hibernate.format_sql">true</property>
<!-- hibernate的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置hibernate的映射文件所在的位置 -->
<mapping resource="Test.hbm.xml" />
</session-factory>
</hibernate-configuration>
(2)在IDEA選項中添加

4、創建數據庫映射文件
Test.hbm.xml
<?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 package="com.text">
<!--
name:即實體類的全名
table:映射到數據庫里面的那個表的名稱
catalog:數據庫的名稱
-->
<class name="Test" table="test" catalog="dss">
<!-- class下必須要有一個id的子元素 -->
<!-- id是用於描述主鍵的 -->
<id name="id" column="id">
<!-- 主鍵生成策略 -->
<generator class="native"></generator>
</id>
<!--
使用property來描述屬性與字段的對應關系
如果length忽略不寫,且你的表是自動創建這種方案,那么length的默認長度是255
-->
<property name="name" column="name" length="255"></property>
<property name="uid" column="uid" length="255"></property>
</class>
</hibernate-mapping>
5、創建hibernate 工具類
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil(){
}
static{
Configuration cfg = new Configuration();
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
return sessionFactory.openSession();
}
}
6、測試類
@RequestMapping(value = "/hibernate",method = RequestMethod.POST)
@ResponseBody
public List<Test> sayHelloll(String name){
Session s = HibernateUtil.getSession(); //這里直接調用HibernateUtil工具類中的getSession()方法獲得Session
Transaction tx = s.beginTransaction(); //開啟事務
Query query = s.createQuery("from Test");
List<Test> test = query.list();
return test;
}
