1、创建项目
2、连接数据库(以MySQL为例)在连接数据库之前,需创建好数据库
3、生成持久化类
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="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=Asia/Shanghai</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据库的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- DB schema will be updated if needed-->
<!-- <property name="hibernate.hbm2ddl.auto">update</property>-->
<mapping class="entity.TestEntity"/>
</session-factory>
</hibernate-configuration>
4、创建测试类,进行测试新增一条数据,hibernate不需要写sql语句,有点类型php的yii2框架,个人认为更好
测试类文件代码
package test;
import entity.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* @author Xuan
* @date 2019/9/20 11:26
*/
public class TestMain {
public static void main(String[] args) {
//加载配置
Configuration configuration = new Configuration();
//读取要读取的配置文件名
configuration.configure("hibernate.cfg.xml");
//创建会话工厂
SessionFactory sessionFactory = configuration.buildSessionFactory();
//生成一次会话
Session session = sessionFactory.openSession();
//开启事务
Transaction transaction = session.beginTransaction();
//实例化实体类 也可以使用构造函数赋值,这里做demo,就不做这么麻烦了
TestEntity test = new TestEntity();
test.setName("小轩");
//保存这个实体类
session.save(test);
//提交事务
transaction.commit();
//关闭会话
session.close();
System.out.println("成功插入一条数据");
}
}
5、运行测试类