一、首先在maven中添加jar包依赖php
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.6.Final</version> </dependency>
二、建立resources文件夹并设置为资源文件夹mysql
三、在resources文件夹中建立hibernate配置文件,两种方法sql
(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选项中添加session
四、建立数据库映射文件app
Test.hbm.xmlmaven
<?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>
五、建立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(); } }
六、测试类测试
@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; }