Home  >  Article  >  Java  >  What is the relationship between persistence classes and entity classes in Java Hibernate?

What is the relationship between persistence classes and entity classes in Java Hibernate?

王林
王林forward
2023-05-08 18:19:181271browse

Hibernate is an open source ORM (Object Relational Mapping) framework, used to map objects in Java programs to relational data in the database. In Hibernate, persistence classes are classes used to map Java objects and relational database tables.

Writing Hibernate persistence classes need to follow the following rules:

  • The persistence class must have a no-argument constructor, otherwise Hibernate cannot create the object.

  • The persistence class must be mapped to a table in the database. You can use the @Table annotation to specify the table name.

  • The attributes of the persistence class must correspond one-to-one with the columns of the database table. You can use the @Column annotation to specify the column name.

  • The persistent class must have a unique identifier, which can be specified using the @Id annotation.

  • The attributes of the persistent class can use the @Basic annotation to specify whether they are basic types, such as strings, numbers, etc.

  • Attributes of persistent classes can be specified using the @Transient annotation and do not need to be persisted to the database.

In Hibernate, there are many primary key generation strategies, common ones include auto-increment, UUID, sequence, etc. You can use the @GeneratedValue annotation to specify the primary key generation strategy, for example:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

The strategy attribute in the @GeneratedValue annotation specifies the primary key generation strategy method, and IDENTITY indicates the use of auto-increment to generate the primary key.

In addition to using annotations to specify the primary key generation strategy, you can also use XML files to configure the primary key generation strategy, for example:

<id name="id" type="java.lang.Long">
    <column name="id" />
    <generator class="identity" />
</id>

The class attribute in the tag specifies the method of primary key generation strategy, and identity means using The primary key is generated by auto-increment.

The three states of Hibernate's persistence class

In Hibernate, the persistence class has three states: transient state, persistent state and free state.

  • Transient state: The persistent class object is not associated with the Session and has not been saved to the database. At this time, the properties of the modified object will not be saved to the database.

  • Persistent state: The persistent class object has been saved to the database and associated with the Session. At this time, the modified object's properties will be saved to the database.

  • Detached state: The persistent object has been saved to the database, but has been disconnected from the Session. At this time, the modified object's properties will not be saved to the database.

You can use the save, persist, update, and merge methods of Session to convert persistent class objects from transient state to persistent state or free state.

The save method is used to save transient state objects to the database and return persistent state objects. If the object is already persistent, no action is performed.

The persist method is used to save transient state objects to the database and does not return persistent state objects. If the object is already persistent, no action is performed.

The update method is used to update the free state object to the database and return the persistent state object. If the object is transient, an exception is thrown.

The merge method is used to merge free state objects into Session and return persistent state objects. If the object is transient, save the object to the database and return the object in persistent state.

Hibernate's first-level cache

Hibernate's first-level cache is a Session-level cache, used to cache persistent class objects. When querying a persistent class object from the database, Hibernate will first search it from the first-level cache. If it does not exist in the cache, it will query it from the database and put the query results into the first-level cache.

The life cycle of the first-level cache is the same as that of the Session. When the Session is closed, the first-level cache will also be cleared. You can use Session's evict and clear methods to clear the first-level cache.

The evict method is used to remove the specified object from the first-level cache, making the object become free.

The clear method is used to clear all objects in the first-level cache and change all persistent objects into a free state.

Hibernate's transaction management

In Hibernate, transactions are used to ensure that operations on the database are atomic, consistent, isolated and durable. You can use the Transaction interface to manage transactions, for example:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try {
    // 执行数据库操作
    tx.commit();
} catch (Exception e) {
    tx.rollback();
} finally {
    session.close();
}

In a transaction, you can use Session's save, persist, update, merge, delete and other methods to operate persistent class objects, and the operations will be performed when the transaction is submitted. The results are saved to the database.

Other APIs of Hibernate

In addition to the APIs introduced above, Hibernate also provides many other APIs, such as:

  • Criteria API: Use For dynamic query of persistent class objects.

  • HQL (Hibernate Query Language): A SQL-based query language used to query persistent class objects.

  • Named Query: Save HQL query statements in persistence classes for easy reuse.

  • Second-level Cache: used to cache persistent class objects to improve query efficiency.

Hibernate's entity class relationship mapping

In Hibernate, the relationship between entity classes can be mapped through annotations, XML configuration files or Java code. Commonly used relationships are one-to-one, one-to-many, many-to-one and many-to-many.

一对一关系

一对一关系表示两个实体类之间的关系是一对一的关系。在Hibernate中,可以使用@OneToOne注解来进行映射。

例如,一个Person实体类和一个IDCard实体类之间的关系是一对一的关系,可以使用如下的代码进行映射:

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
    private IDCard idCard;
    // getters and setters
}
@Entity
public class IDCard {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String number;
    @OneToOne
    @JoinColumn(name = "person_id")
    private Person person;
    // getters and setters
}

其中,Person实体类中使用了@OneToOne注解来映射与IDCard实体类的关系,属性mappedBy指定了IDCard实体类中的person属性与Person实体类中的idCard属性之间的关系,cascade属性指定了级联操作。

IDCard实体类中使用了@OneToOne注解来映射与Person实体类的关系,属性JoinColumn指定了Person实体类中与IDCard实体类关联的外键列名。

一对多关系

一对多关系表示一个实体类可以对应多个另一个实体类的对象。在Hibernate中,可以使用@OneToMany注解来进行映射。

例如,一个Department实体类中有多个Employee实体类的对象,可以使用如下的代码进行映射:

@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
    private List<Employee> employees;
    // getters and setters
}
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
    // getters and setters
}

其中,Department实体类中使用了@OneToMany注解来映射与Employee实体类的关系,属性mappedBy指定了Employee实体类中的department属性与Department实体类中的employees属性之间的关系,cascade属性指定了级联操作。

Employee实体类中使用了@ManyToOne和@JoinColumn注解来映射与Department实体类的关系,属性JoinColumn指定了Department实体类中与Employee实体类关联的外键列名。

多对一关系

多对一关系表示多个实体类可以对应一个另一个实体类的对象。在Hibernate中,可以使用@ManyToOne注解来进行映射。

例如,一个Employee实体类所属于一个Department实体类,可以使用如下的代码进行映射:

@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters and setters
}
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
    // getters and setters
}

其中,Employee实体类中使用了@ManyToOne和@JoinColumn注解来映射与Department实体类的关系,属性JoinColumn指定了Department实体类中与Employee实体类关联的外键列名。

多对多关系

多对多关系表示多个实体类之间互相关联。在Hibernate中,可以使用@ManyToMany注解来进行映射。

例如,一个Student实体类可以选择多个Course实体类,一个Course实体类也可以有多个Student实体类,可以使用如下的代码进行映射:

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToMany(mappedBy = "students", cascade = CascadeType.ALL)
    private List<Course> courses;
    // getters and setters
}
@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @ManyToMany
    @JoinTable(
        name = "course_student",
        joinColumns = @JoinColumn(name = "course_id"),
        inverseJoinColumns = @JoinColumn(name = "student_id")
    )
    private List<Student> students;
    // getters and setters
}

其中,Student实体类中使用了@ManyToMany注解来映射与Course实体类的关系,属性mappedBy指定了Course实体类中的students属性与Student实体类中的courses属性之间的关系,cascade属性指定了级联操作。

Course实体类中使用了@ManyToMany和@JoinTable注解来映射与Student实体类的关系,属性JoinTable指定了关联表的名称和两个实体类之间的关联关系。

The above is the detailed content of What is the relationship between persistence classes and entity classes in Java Hibernate?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete