📜  使用 JPA 和 MySQL 的休眠示例

📅  最后修改于: 2022-05-13 01:54:36.913000             🧑  作者: Mango

使用 JPA 和 MySQL 的休眠示例

Hibernate 是一个提供一些抽象层的框架,这意味着程序员不必担心实现,Hibernate 会在内部为您完成实现,例如编写查询以执行 CRUD 操作、建立与数据库的连接等。它是一个用于开发持久性逻辑的Java框架。更准确地说,Hibernate 是一个开源的、非侵入性的、轻量级的Java ORM(对象关系映射)框架,用于开发独立于数据库软件的对象,并在所有Java、JEE 中制作独立的持久化逻辑。

JPA 代表Java持久性 API 。它被称为Java规范,它为 ORM 工具提供了一些功能和标准。它用于控制、审查和持久化Java对象和数据库之间的数据。它被视为对象关系映射的标准技术。有时 Geeks 会混淆 JPA 和 Hibernate。所以这里是 JPA 和 Hibernate 之间的一些基本区别。

JPA

Hibernate

JPA is not an implementation. It is only a Java specification.Hibernate is an implementation of JPA.
JPA explains the handling of data in Java applications.Hibernate is an ORM (Object-Relational Mapping) tool that is used to save the Java objects in the database system.
As an object-oriented query language, JPA uses JPQL (Java Persistence Query Language) to execute database operations.As an object-oriented query language, it uses Hibernate Query Language (HQL) to execute database operations.

实现:我们将通过创建一个 maven 项目来构建一个简单的Java应用程序,我们将在 Hibernate 和 JPA 概念的帮助下将一些数据保存在 MySQL 数据库中。

第 1 步:在您喜欢的Java IDE 中创建一个 maven 项目(在本文中,我们使用的是 IntelliJ IDEA)

第 2 步:成功创建 maven 项目后,您必须在pom.xml文件中添加一些依赖项。您必须在 pom.xml 文件中添加以下依赖项。

Hibernate的依赖如下:

XML

  org.hibernate.orm
  hibernate-core
  6.0.0.Alpha8


XML

  mysql
  mysql-connector-java
  5.0.8


XML


    4.0.0
 
    org.example
    hibernateapp
    1.0-SNAPSHOT
 
    
        
            org.hibernate.orm
            hibernate-core
            6.0.0.Alpha8
        
        
            mysql
            mysql-connector-java
            5.0.8
        
    
 
    
        11
        11
    
 


Java
// Java Program to Illustrate Creation of Simple POJO Class
 
// Importing required classes
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "song")
 
// POJO class
public class Song {
 
    @Id @Column(name = "songId") private int id;
 
    @Column(name = "songName") private String songName;
 
    @Column(name = "singer") private String artist;
 
    public int getId() { return id; }
 
    public void setId(int id) { this.id = id; }
 
    public String getSongName() { return songName; }
 
    public void setSongName(String songName)
    {
        this.songName = songName;
    }
 
    public String getArtist() { return artist; }
 
    public void setArtist(String artist)
    {
        this.artist = artist;
    }
}


XML



    
 
        
        jdbc:mysql://localhost:3306/hibernate-demo(your schema name)
 
        
        your MySQL user name
 
        
        your MySQL password
 
        
        com.mysql.cj.jdbc.Driver
 
        true
 
    


Java
// Java Program to Illustrate App File
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
// Main class
public class App {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Create Configuration
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        configuration.addAnnotatedClass(Song.class);
 
        // Create Session Factory
        SessionFactory sessionFactory
            = configuration.buildSessionFactory();
 
        // Initialize Session Object
        Session session = sessionFactory.openSession();
 
        Song song1 = new Song();
 
        song1.setId(1);
        song1.setSongName("Broken Angel");
        song1.setArtist("Akon");
 
        session.beginTransaction();
 
        // Here we have used
        // save() method of JPA
        session.save(song1);
 
        session.getTransaction().commit();
    }
}



MySQL的依赖关系如下:

XML


  mysql
  mysql-connector-java
  5.0.8


示例: pom.xml 文件

XML



    4.0.0
 
    org.example
    hibernateapp
    1.0-SNAPSHOT
 
    
        
            org.hibernate.orm
            hibernate-core
            6.0.0.Alpha8
        
        
            mysql
            mysql-connector-java
            5.0.8
        
    
 
    
        11
        11
    
 


第 3 步:创建一个简单的 POJO 类并将该类命名为 Song。

Java

// Java Program to Illustrate Creation of Simple POJO Class
 
// Importing required classes
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "song")
 
// POJO class
public class Song {
 
    @Id @Column(name = "songId") private int id;
 
    @Column(name = "songName") private String songName;
 
    @Column(name = "singer") private String artist;
 
    public int getId() { return id; }
 
    public void setId(int id) { this.id = id; }
 
    public String getSongName() { return songName; }
 
    public void setSongName(String songName)
    {
        this.songName = songName;
    }
 
    public String getArtist() { return artist; }
 
    public void setArtist(String artist)
    {
        this.artist = artist;
    }
}


第 4 步:src > main > resources文件夹中创建一个休眠配置文件(XML 文件)。在这里,我们将文件命名为hibernate.cfg.xml 。在这个文件中,我们将为MySQL 数据库配置所有属性。

示例: hibernate.cfg.xml 文件

XML




    
 
        
        jdbc:mysql://localhost:3306/hibernate-demo(your schema name)
 
        
        your MySQL user name
 
        
        your MySQL password
 
        
        com.mysql.cj.jdbc.Driver
 
        true
 
    


第 5 步:创建一个名为App的类,并在该类中编写 main() 方法

例子

Java

// Java Program to Illustrate App File
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
// Main class
public class App {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Create Configuration
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        configuration.addAnnotatedClass(Song.class);
 
        // Create Session Factory
        SessionFactory sessionFactory
            = configuration.buildSessionFactory();
 
        // Initialize Session Object
        Session session = sessionFactory.openSession();
 
        Song song1 = new Song();
 
        song1.setId(1);
        song1.setSongName("Broken Angel");
        song1.setArtist("Akon");
 
        session.beginTransaction();
 
        // Here we have used
        // save() method of JPA
        session.save(song1);
 
        session.getTransaction().commit();
    }
}


第 6 步:在 MySQL 数据库中创建一个名为hibernate-demo的模式(您可以选择自己的模式)。并运行您的应用程序。

输出:

MySQL Workbench 中的输出