【Hibernate】Re01 快速入門


 

官網地址:

http://hibernate.org/orm/releases/5.4/

地址:

https://bintray.com/hibernate/artifacts/hibernate-orm

只需要一個坐標就搞好了

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-agroal</artifactId>
    <version>5.4.21.Final</version>
    <type>pom</type>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.20</version>
</dependency>

編寫新聞實體類:

package cn.zeal4j.domain;

import java.util.Date;

/**
 * @author Administrator
 * @file Hibernate
 * @create 2020 09 23 16:06
 */
public class News {
    private Integer id;
    private String title;
    private String author;
    private Date date;

    public News() {
    }

    public News(Integer id, String title, String author, Date date) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.date = date;
    }

    @Override
    public String toString() {
        return "News{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", date=" + date +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

編寫Hibernate核心配置XML【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://IP-Address:Port/hibernate?serverTimezone=Asia/Shanghai</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.username">Username</property>
        <property name="connection.password">Password</property> 

        <property name="dialect">org.hibernate.dialect.MySQL57Dialect</property> <!-- 數據庫版本方言 -->
        <property name="show_sql">true</property> <!-- 是否讓控制台輸出SQL語句 -->
        <property name="format_sql">true</property> <!-- 控制台輸出的SQL格式化 -->
        <property name="hbm2ddl.auto">update</property> <!-- 數據庫表的生成策略 -->

        <mapping resource="hibernate/mapping/News.hbm.xml" /> <!-- 實體類映射XML路徑 -->
    </session-factory>
    
</hibernate-configuration>

編寫映射配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.zeal4j.domain" > <!-- 實體類包映射 -->

    <class name="News" table="news" >  <!-- 實體類配置 -->
        <id name="id" column="id"  type="java.lang.Integer"> <!-- 主鍵與維護策略 -->
            <generator class="increment" /> <!-- 發現官方提供的策略很嚴格,必須increment 其他的策略都會報錯說 主鍵沒有默認值 -->
            <!--<generator class="assigned" />-->
            <!--<generator class="native" />-->
        </id>
        <property name="title" column="title" type="java.lang.String" /> <!-- 類屬性 表字段 java類型 -->
        <property name="author" column="author" type="java.lang.String" />
        <property name="date" column="date" type="java.util.Date" /> <!-- 默認的util包的Date即可,不要使用sql包的 -->
    </class>

</hibernate-mapping>

測試運行:

package cn.zeal4j;
import cn.zeal4j.domain.News;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.junit.Test;
import java.io.Serializable;
import java.util.Date;

/**
 * @author Administrator
 * @file Hibernate
 * @create 2020 09 23 16:16
 */
public class HibernateTest {

    @Test
    public void quickStart() {
        Transaction transaction = null;
        Session session = null;
        SessionFactory sessionFactory = null;
        try {
            //  但在5.1.0版本匯總,hibernate則采用如下新方式獲取:
            //  1. 配置類型安全的准服務注冊類,這是當前應用的單例對象,不作修改,所以聲明為final
            //  在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認在類路徑下尋找名為hibernate.cfg.xml的文件
            final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate/hibernate.cfg.xml").build();
            
            //  2. 根據服務注冊類創建一個元數據資源集,同時構建元數據並生成應用一般唯一的的session工廠
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();

            /* - - - - - - - 上面是配置准備,下面開始我們的數據庫操作 - - - - - - - */
            session = sessionFactory.openSession(); //從會話工廠獲取一個session

            transaction = session.beginTransaction();

            News news = new News(null, "新聞標題:這是一段演示文本...", "作者:Zeal4J", new Date());

            Serializable save = session.save(news);

            System.out.println("操作結果:" + save);

            transaction.commit();

        } catch (Exception exception) {
            exception.printStackTrace();
            transaction.rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
    }
}

輸出的SQL語句:

Hibernate: 
    select
        max(id) 
    from
        news
操作結果:3
Hibernate: 
    insert 
    into
        news
        (title, author, date, id) 
    values
        (?, ?, ?, ?)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM