📜  休眠 – 注释

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

休眠 – 注释

Java中的注释用于表示补充信息。正如您所见,@override、@inherited 等是一般Java语言中的注释示例。如需深入了解,请参阅Java中的注释。在本文中,我们将讨论称为 hibernate 的注解。因此,使用 hibernate 的动机是跳过 SQL 部分并专注于核心Java概念。通常,在 hibernate 中,我们使用 XML 映射文件将 POJO 类数据转换为数据库数据,反之亦然。但是使用 XML 会变得有点混乱,因此,为了替代使用 XML,我们直接在 POJO 类中使用注释来声明更改。在 POJO 类内部使用注释也使事情变得简单易记和易于使用。 Annotation 是一种为数据库表提供元数据的强大方法,它同时提供有关数据库表结构和 POJO 类的简要信息。

设置 Hibernate 注释项目

建议为休眠设置Maven项目,因为将依赖项从官方 Maven 存储库复制粘贴到您的pom.xml 中变得很容易。

第 1 步:创建 Maven 项目(Intellj)

转到下一步并命名一个项目,然后单击完成。

第二步:在 pom.xml 文件中添加依赖

建立一个 maven 项目后,默认情况下,你会得到一个 POM.xml 文件,它是一个依赖文件。 POM 代表项目对象模型,它允许我们从 1 个位置添加或删除依赖项。

项目结构和 pom.xml 应该如下所示。现在,添加 hibernate 和 MySQL 依赖项以使用注释创建表并使用 HQL(hibernate 查询语言)。

pom.xml 文件

XML


    4.0.0
  
    org.example
    Hibernateproject
    1.0-SNAPSHOT
  
    
        11
        11
    
  
    
        
        
            org.hibernate
            hibernate-core
            5.6.5.Final
        
  
        
        
            mysql
            mysql-connector-java
            8.0.28
        
  
    
  


XML



    
            
          
        
            com.mysql.cj.jdbc.Driver
        
  
        
        
            jdbc:mysql://localhost:3306/student
        
          
          
        
            root  
        
  
        
            your_password
        
  
           
        org.hibernate.dialect.MySQL5Dialect
  
           
        update
  
        
          
        
  
    
    


Java
package com.student;
import javax.persistence.*;
  
// Entity is declare to make this class an object for the
// database
@Entity
// By default hibernate will name the table Student as class
// name but @Table annotation override it to students
@Table(name = "students")
public class Student {
    // @id make stuid as a primary key and @GeneratedValue
    // auto increment
    @Id
    @GeneratedValue
    // This will override and make column name id in place
    // of stuid
    @Column(name = "id")
    private int stuid;
    // This will override and make column name full name in
    // place of name
    @Column(name = "Full_name") private String name;
    // This will override and make column name Age in place
    // of age
    @Column(name = "Age") private int age;
    // This will override and make column name Department in
    // place of stream
    @Column(name = "Department") private String stream;
  
    //    Basic getters and setters to set and get values
    public int getStuid() { return stuid; }
  
    public void setStuid(int stuid) { this.stuid = stuid; }
  
    public String getName() { return name; }
  
    public void setName(String name) { this.name = name; }
  
    public int getAge() { return age; }
  
    public void setAge(int age) { this.age = age; }
  
    public String getStream() { return stream; }
  
    public void setStream(String stream)
    {
        this.stream = stream;
    }
}


Java
package com.student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
  
public class Main {
    public static void main(String[] args)
    {
  
        // Setting the objects
        Student s = new Student();
        s.setStuid(1);
        s.setName("Geek");
        s.setAge(22);
        s.setStream("Computer science");
  
        // activate hibernate network
        Configuration cfg = new Configuration();
  
        // We use sessionfactory to build a session for
        // database and hibernate
        SessionFactory factory
            = cfg.configure("hibernate.cfg.xml")
                  .buildSessionFactory();
  
        // opening a session
        Session session = factory.openSession();
  
        // Transaction is a java object used to give the
        // instructions to database
        Transaction tx = session.beginTransaction();
  
        // we use save to provide the object to push in
        // database table
        session.save(s);
  
        // commit is a transaction function used to push
        // some changes to database with reference to hql
        // query
        tx.commit();
  
        session.close();
    }
}


确保添加依赖项,它应该看起来像上面的文件。

第 3 步:为数据库参数添加 hibernate.cfg.xml 文件

我们使用 hibernate.cfg.xml 文件来提供所有相关的数据库参数,如数据库用户名、密码、本地主机等。确保在资源文件夹中创建hibernate.cfg.xml

休眠.cfg.xml

XML




    
            
          
        
            com.mysql.cj.jdbc.Driver
        
  
        
        
            jdbc:mysql://localhost:3306/student
        
          
          
        
            root  
        
  
        
            your_password
        
  
           
        org.hibernate.dialect.MySQL5Dialect
  
           
        update
  
        
          
        
  
    
    

该文件应如上所示

第 4 步:添加 POJO 和主要类以使用该功能

以下是我们的 POJO 中使用的一些注解,专门用于 hibernate-

Annotations

Use of annotations

@Entity Used for declaring any POJO class as an entity for a database
@Table

Used to change table details, some of the attributes are-

  • name – override the table name
  • schema
  • catalogue
  • enforce unique contrants
@IdUsed for declaring a primary key inside our POJO class
@GeneratedValueHibernate automatically generate the values with reference to the internal sequence and we don’t need to set the values manually.
@Column

It is used to specify column mappings. It means if in case we don’t need the name of the column that we declare in POJO but we need to refer to that entity you can change the name for the database table. Some attributes are-

  • Name – We can change the name of the entity for the database
  • length – the size of the column mostly used in strings
  • unique – the column is marked for containing only unique values
  • nullable – The column values should not be null. It’s marked as NOT
@TransientTells the hibernate, not to add this particular column
@TemporalThis annotation is used to format the date for storing in the database
@LobUsed to tell hibernate that it’s a large object and is not a simple object
@OrderBy

This annotation will tell hibernate to OrderBy as we do in SQL.

For example – we need to order by student first name in ascending order

@OrderBy(“firstName asc”) 

这些是主要用于与休眠一起使用的一些注释。

学生。 Java (POJO 类)

Java

package com.student;
import javax.persistence.*;
  
// Entity is declare to make this class an object for the
// database
@Entity
// By default hibernate will name the table Student as class
// name but @Table annotation override it to students
@Table(name = "students")
public class Student {
    // @id make stuid as a primary key and @GeneratedValue
    // auto increment
    @Id
    @GeneratedValue
    // This will override and make column name id in place
    // of stuid
    @Column(name = "id")
    private int stuid;
    // This will override and make column name full name in
    // place of name
    @Column(name = "Full_name") private String name;
    // This will override and make column name Age in place
    // of age
    @Column(name = "Age") private int age;
    // This will override and make column name Department in
    // place of stream
    @Column(name = "Department") private String stream;
  
    //    Basic getters and setters to set and get values
    public int getStuid() { return stuid; }
  
    public void setStuid(int stuid) { this.stuid = stuid; }
  
    public String getName() { return name; }
  
    public void setName(String name) { this.name = name; }
  
    public int getAge() { return age; }
  
    public void setAge(int age) { this.age = age; }
  
    public String getStream() { return stream; }
  
    public void setStream(String stream)
    {
        this.stream = stream;
    }
}

主要的。 Java (动作类)

Java

package com.student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
  
public class Main {
    public static void main(String[] args)
    {
  
        // Setting the objects
        Student s = new Student();
        s.setStuid(1);
        s.setName("Geek");
        s.setAge(22);
        s.setStream("Computer science");
  
        // activate hibernate network
        Configuration cfg = new Configuration();
  
        // We use sessionfactory to build a session for
        // database and hibernate
        SessionFactory factory
            = cfg.configure("hibernate.cfg.xml")
                  .buildSessionFactory();
  
        // opening a session
        Session session = factory.openSession();
  
        // Transaction is a java object used to give the
        // instructions to database
        Transaction tx = session.beginTransaction();
  
        // we use save to provide the object to push in
        // database table
        session.save(s);
  
        // commit is a transaction function used to push
        // some changes to database with reference to hql
        // query
        tx.commit();
  
        session.close();
    }
}

输出:

输出