MySQL 如何将Hibernate连接到MySQL数据库

MySQL 如何将Hibernate连接到MySQL数据库

在本文中,我们将看到如何使用ORM(对象关系映射)框架Hibernate连接到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>

现在,让我们定义一个实体类,它将使用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>

Session 工厂用于管理会话的创建和生命周期。我们需要每个数据库一个会话工厂。

会话用于创建与数据库的连接/会话。

在这里,create-drop会检查表是否已经存在,然后它将首先删除表,然后创建新表。

Dialect代表了我们在数据库中使用的MySQL版本。

阅读更多: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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程