maven hibernat mysql_maven 配置Hibernate

这篇博客介绍了如何在Maven项目中配置Hibernate以连接MySQL数据库,包括添加Maven依赖,设置资源文件夹,创建Hibernate配置文件和数据库映射文件,编写Hibernate工具类以及进行测试操作。
摘要由CSDN通过智能技术生成

1、首先在maven中添加jar包依赖

org.hibernate

hibernate-core

5.2.6.Final

2、创建resources文件夹并设置为资源文件夹

9cca9e42a6a50b697b3f6460503e1f0c.png

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选项中添加

9f388d3ef2e559e344caa092c24bfeef.png

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值