Hibernate 框架学习

时间:2023-03-08 20:27:23
Hibernate 框架学习

什么是hibernate框架?

1.它是应用在javaee 三层架构中的dao层 它的底层就是JDBC 它对JDBC进行了封装,好处就是不用写jdbc的代码,和sql语句,它是一个开源的轻量级框架,现在使用hibernate5.x版本

入门使用:

1. 导入hibernate所需要的jar文件

2.创建实体类  (User类 例:com.bin.User)

3.在com.bin.User 这个包中 创建相对应的xml文件 (User.hbm.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!--引入hiberbate 约束文件-->
<!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="bin.superme.pojo.User" table="User_bin">
<id name="uid" column="id">
<generator class="uuid"></generator>
</id>
<property name="username" column="user_name"></property>
<property name="password" column="pass_word"></property>
</class>

</hibernate-mapping>

4.创建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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!--注册驱动-->
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_test</property> <!--数据库路径-->
<property name="hibernate.connection.username">root</property> <!--数据库账号-->
<property name="connection.password">cjx</property> <!--数据库密码-->
<!--hibernate 自身配置-->
<property name="show_sql">true</property> <!--是否显示Sql语句-->
<property name="format_sql">true</property> <!--是否格式化sql语句-->
<property name="hibernate.hbm2ddl.auto">update</property> <!--数据库自动更新-->
<!--配置数据库的方言-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!--配置User.hbm.xml 的映射关系-->
<mapping resource="bin/superme/pojo/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
5.创建测试类
package bin.superme.test;

import bin.superme.pojo.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration; public class User_Test {
public static void main(String[] args) {
//加载hibernate 的核心配置文件
Configuration cfg = new Configuration();
cfg.configure();
//创建 SessionFactory 对象
SessionFactory sessionFactory = cfg.buildSessionFactory();
//获取SessionFactory的链接
Session session = sessionFactory.openSession();
//开启事务
Transaction tran = session.beginTransaction();
//写业务逻辑
User user = new User();
user.setUsername("张6");
user.setPassword("qwe123");
session.save(user);
//提交事务
tran.commit();
//关闭
session.close();
sessionFactory.close();
}
}