idea2019搭建Hibernate框架環境demo

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、運行測試類

在這裏插入圖片描述
在這裏插入圖片描述

6、遇到困難可以評論(有信必回)小軒微信17382121839。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章