如何使用Hibernate連線MySQL資料庫?


在這篇文章中,我們將學習如何使用Hibernate這樣的ORM(物件關係對映)框架連線MySQL資料庫。

首先,我們需要在我們的pom.xml檔案中新增Hibernate的Maven依賴項:

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.2.Final</version> </dependency> Now, let us define an entity class that will be mapped to a database table using hibernate. @Entity @Table( name = " Employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Column(name = "first_name") String firstName; @Column(name = "last_name") String lastName; //Getters //Setters }

這裡:

@Table 用於指定此類將對映到的表名。

@Entity 將類對映到關係資料庫表。

@Id 將在表的給定屬性上建立一個主鍵。

@GeneratedValue 指定用於生成屬性值的策略。Strategy=GenerationType.AUTO表示它將自動遞增。

現在,我們需要為Hibernate定義一個名為hibernate.cfg.xml的配置檔案。Hibernate將使用此配置檔案連線到提供的資料庫。

<!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> <!-- JDBC Database connection settings --> <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/dbName?useSSL=false</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool settings ... using built-in test pool --> <property name="connection.pool_size">1</property> <!-- Echo the SQL to stdout --> <property name="show_sql">true</property> <!-- Select our SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create-drop</property> <!-- name of annotated entity class --> <mapping class="academy.company.Employee"/> </session-factory> </hibernate-configuration>

SessionFactory管理會話的建立和生命週期。每個資料庫都需要一個SessionFactory。

Session用於建立與資料庫的連線/會話。

這裡,create-drop將檢查表是否已存在,然後它將首先刪除表,然後建立一個新表。

Dialect表示我們在資料庫中使用的MySQL版本。

示例

在執行Java應用程式之前,我們只需要在Main.java中配置SessionFactory:

package academy.company; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Main { public static void main(String[] args) { SessionFactory sessionFactory; sessionFactory = new Configuration() .configure("academy/company/hibernate.cfg.xml") .buildSessionFactory(); } }

現在,當我們啟動Java應用程式時,我們可以在控制檯中看到Hibernate將首先刪除Employee表(如果已存在)。如果不存在,它將使用我們在employee類中定義的屬性建立Employee表。

輸出

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists Employee

Jan 08, 2022 1:26:32 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection

INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@eca6a74] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.

Hibernate: drop table if exists hibernate_sequence
Hibernate: create table Employee (id bigint not null, first_name varchar(255), last_name varchar(255), primary key (id)) engine=MyISAM

更新於:2022年8月26日

8K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告