ORM:Object Relational Mapping (对象关系映射)将java中的对象和关系数据库中的表建立一种映射(实现操作对象就可以操作数据中的表)
Hibernate:Hibernate是一个持久层的ORM框架
Hibernate环境搭建:
- 首先要导入Hibernate所需要的jar包,mysql驱动,log4j日志的3个jar包
- 在mysql中创建表如:customer
- 在idea中创建实体类,如:Customer,类中的属性与表中的列名相对应,然后生成get、set方法
- 创建映射:
- 命名规范:类名.hbm.xml
- 引入约束(xml文件的知识):在hibernate-core的jar包下找到hibernate-mapping-3.0.dtd的类似文件找到
<!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.bean.Customer" table="customer"> <!--id 是用来建立类中的属性与表中的主键对应--> <id name="cust_id" column="cust_id"> <generator class="native"></generator> </id> <!--建立类中的普通属性与表的其他字段相对应--> <property name="cust_name" column="cust_name"></property> <property name="cust_source" column="cust_source"></property> <property name="cust_industry" column="cust_industry"></property> <property name="cust_level" column="cust_level"></property> <property name="cust_phone" column="cust_phone"></property> <property name="cust_mobile" column="cust_mobile"></property> </class> </hibernate-mapping>
- hibernate的核心配置文件:
- 命名:hibernate.cfg.xml
- 引入约束:在hibernate-core的jar包下找到hibernate-configuration-3.0.dtd的类似文件找到:
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
-
基本配置:
<hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/shop?useSSL=false&serverTimezone=Hongkong</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!--配置Hibernate方言--> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="com/bean/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
- 编写测试类:
- 加载hibernate核心配置文件
- 创建一个SessionFactory对象(类似于JDBC连接池)
- 通过SessionFactory获取到Session对象(类似于JDBC中的Connection)
- 手动开启事务
- 编写代码
- 提交事务
- 释放资源
@Test public void demo1(){ // 1.加载hibernate核心配置文件 Configuration configuration = new Configuration().configure(); // 2.创建一个SessionFactory对象(类似于JDBC连接池) SessionFactory sessionFactory = configuration.buildSessionFactory(); // 3.通过SessionFactory获取到Session对象(类似于JDBC中的Connection) Session session=sessionFactory.openSession(); // 4.手动开启事务 Transaction transaction = session.beginTransaction(); // 5.编写代码 Customer customer = new Customer(); customer.setCust_name("赵云"); session.save(customer); // 6.提交事务 transaction.commit(); // 7.释放资源 session.close(); }