maven 配置Hibernate
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;
}

浙公网安备 33010602011771号