1、首先在maven中添加jar包依赖
org.hibernate
hibernate-core
5.2.6.Final
2、创建resources文件夹并设置为资源文件夹
3、在resources文件夹中创建hibernate配置文件,两种方法
(1)、直接创建hibernate.cfg.xml
/p>
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
thread
com.mysql.jdbc.Driver
jdbc:mysql://localhost/dss
root
123
true
true
org.hibernate.dialect.MySQLDialect
(2)在IDEA选项中添加
4、创建数据库映射文件
Test.hbm.xml
/p>
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
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 sayHelloll(String name){
Session s = HibernateUtil.getSession(); //这里直接调用HibernateUtil工具类中的getSession()方法获得Session
Transaction tx = s.beginTransaction(); //开启事务
Query query = s.createQuery("from Test");
List test = query.list();
return test;
}