1.创建项目
首先通过IDEA创建一个MAVEN项目,创建lib文件夹,导入相关jar包。
2.创建数据库
新建名为hibernattest的数据库,建立一张user表,表结构如下
代码如下:
CREATE TABLE `lzy_user` (
`id` bigint(20) NOT NULL,
`name` varchar(50) DEFAULT NULL,
`birthday` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
3.添加Hibernate配置文件
创建resources文件夹,添加xml
代码如下:
<hibernate-configuration>
<!-- 通常,一个session-factory节点代表一个数据库 -->
<session-factory>
<!-- 1. 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hibernatetest?serverTimezone=GMT%2B8&useSSL=false</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!--
数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 2. 其他相关配置 -->
<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 2.2 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- 2.3 自动建表 -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!--3. 加载所有映射-->
<mapping resource="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
配置xml映射文件
代码如下:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.lzy.pojo.User" lazy="true" table="lzy_user">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="name" column="name"/>
<property name="birthday" column="birthday"/>
</class>
</hibernate-mapping>
4.使用Hibernate实现用户添加
使用Hibernate的步骤:
读取配置文件
创建SessionFactory,SessionFactory是Session的工厂,代表一个连接的工厂,用来生产Session,与mybatis中的功能类似
打开Session,使用openSession方法创建一个对象,代表一个连接,通过Session行使curd功能
开启一个事务
持久化操作
提交事务
关闭Session
代码如下:
package com.lzy;
import com.lzy.pojo.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Configuration conf = new Configuration().configure();//1、读取配置文件
SessionFactory sf = conf.buildSessionFactory();// 2、创建SessionFactory
Session session = sf.openSession();// 3、打开Session
Transaction tx = null;
try{
tx = session.beginTransaction();// 4、开始一个事务
// 5、持久化操作
User user = new User();
user.setBirthday(new Date());
user.setName("lzy");
session.save(user);
tx.commit();// 6、 提交事务
}catch(Exception e){
if (null!=tx){tx.rollback();}
e.printStackTrace();
}finally{
session.close();// 7、关闭Session
}
}
}
控制台运行结果如下: