Hibernate of Java Framework: Make Data Persistence So Easy

In the Java world, Hibernate is a very popular object-relational mapping (ORM) framework that provides developers with a simple and powerful tool for mapping object models to relational databases. Hibernate not only simplifies the process of data persistence, but also improves development efficiency and code maintainability. This article will give you a detailed introduction to the charm of Hibernate, let us explore the wonderful world of this Java framework together!

1. Understanding Hibernate

Hibernate is an open source Java persistence framework that simplifies the process of saving objects to the database. By using Hibernate, developers can apply object-oriented thinking throughout the entire development process without paying too much attention to underlying database operations. Hibernate converts Java objects into records in the database through mapping files and annotations, and implements object-relational mapping.

Second, the advantages of Hibernate

  1. Simplified data persistence operation: Hibernate automatically completes the conversion of object-relational mapping, so that developers do not need to write a large number of SQL statements, thus simplifying the process of data persistence.
  2. Improve development efficiency: With Hibernate, developers can focus on the development of business logic without spending too much time on the data access layer. In addition, Hibernate also supports a variety of databases, allowing developers to quickly switch databases.
  3. Enhance code maintainability: The declarative data persistence operation provided by Hibernate makes the code more concise and easy to maintain. In addition, Hibernate also provides rich annotations and XML mapping files, making the code structure clearer.

Three, the core components of Hibernate

  1. Configuration file: Hibernate's configuration file (usually hibernate.cfg.xml or hibernate.hbm.xml) defines information such as database connections and mapping files.
  2. Mapping file: The mapping file (in the form of .hbm.xml or annotation) defines the mapping relationship between Java classes and database tables.
  3. SessionFactory: SessionFactory is one of the core components of Hibernate, which is responsible for creating and managing Session objects. Session is an object used to perform database operations.
  4. Session: Session provides methods to perform CRUD (create, read, update, delete) operations, and it is the main interface for interacting with the database.
  5. Query: The Query object is used to perform a query operation, which can retrieve data that meets specified conditions from the database. Hibernate provides a variety of query methods, such as HQL (Hibernate Query Language) and Criteria API.

Fourth, the basic usage of Hibernate

  1. Configure Hibernate: configure Hibernate configuration files according to project requirements, including database connection information, transaction manager, etc.
  2. Create a mapping file: create or use annotations to specify a mapping file for each Java class, and define the mapping relationship between the class and the database table.
  3. Create SessionFactory: Create a SessionFactory object according to the configuration file, which is responsible for creating and managing Session objects.
  4. Create Session: Get the Session object from SessionFactory to perform database operations.
  5. Perform CRUD operations: Use the API provided by the Session object to perform CRUD operations, such as save(), get(), delete(), etc.
  6. Close Session and SessionFactory: After completing the database operation, remember to close Session and SessionFactory to release resources.

V. Summary

As a popular Java persistence framework, Hibernate provides developers with powerful data persistence tools. With Hibernate, developers can perform data persistence operations more efficiently while improving code maintainability. This article introduces the core components and basic usage of Hibernate in detail, hoping to help you!

The following is an example of a simple Java integration with the Hibernate framework:

1. Add Hibernate dependency

In a Maven project, add the following dependencies to the pom.xml file:

<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate-core</artifactId>  
    <version>5.5.7.Final</version>  
</dependency>

2. Configure the Hibernate configuration file

Create a configuration file called hibernate.cfg.xml and place it in the src/main/resources directory. In the configuration file, specify the database connection information, transaction manager and other information

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
<hibernate-configuration>  
    <session-factory>  
        <!-- 数据库连接信息 -->  
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>  
        <property name="hibernate.connection.username">root</property>  
        <property name="hibernate.connection.password">password</property>  
        <!-- 其他配置 -->  
        <!-- ... -->  
    </session-factory>  
</hibernate-configuration>

3. Create entity class

Create an entity class called User that maps the user table in the database. Add corresponding properties and getter/setter methods to the class.

import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.GenerationType;  
import javax.persistence.Id;  
  
@Entity  
public class User {  
    @Id  
    @GeneratedValue(strategy = GenerationType.AUTO)  
    private Long id;  
    private String name;  
    private Integer age;  
    // getter and setter methods  
}

4. Create a mapping file

Create a mapping file called User.hbm.xml and place it in the src/main/resources directory. In the mapping file, specify the mapping relationship between entity classes and database tables.

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="com.example.User">  
        <id name="id" column="id">  
            <generator class="auto"/>  
        </id>  
        <property name="name" column="name"/>  
        <property name="age" column="age"/>  
    </class>  
</hibernate-mapping>

5. Create a Hibernate configuration class

Create a configuration class called HibernateConfig that loads the Hibernate configuration file and creates a SessionFactory object. Create a SessionFactory object using Java's reflection mechanism in the class.

import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.orm.hibernate5.HibernateTemplate;  
import org.springframework.orm.hibernate5.HibernateTransactionManager;  
import org.springframework.transaction.annotation.EnableTransactionManagement;  
import org.springframework.transaction.annotation.TransactionManagementConfigurer;  
import javax.annotation.Resource;  
import java.util.*;  
  
@Configuration  
@EnableTransactionManagement  
public class HibernateConfig {  
  
    @Bean  
    public SessionFactory sessionFactory() {  
        Configuration configuration = new Configuration();  
        configuration.configure("hibernate.cfg.xml");  
        return configuration.buildSessionFactory();  
    }  
  
    @Bean  
    public HibernateTemplate hibernateTemplate() {  
        HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory());  
        return hibernateTemplate;  
    }  
  
    @Bean  
    public HibernateTransactionManager transactionManager() {  
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory());  
        return transactionManager;  
    }  
}

6. Create DAO class

Create a DAO class named UserDao for interacting with the database. Use HibernateTemplate in the class to perform CRUD operations.

import org.springframework.orm.hibernate5.HibernateTemplate;  
import com.example.User;  
import java.util.*;  
  
public class UserDao {  
  
    private HibernateTemplate hibernateTemplate;  
  
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {  
        this.hibernateTemplate = hibernateTemplate;  
    }  
  
    public User getUserById(Long id) {  
        return (User) hibernateTemplate.get(User.class, id);  
    }  
  
    public void addUser(User user) {  
        hibernateTemplate.save(user);  
    }  
  
    public void updateUser(User user) {  
        hibernateTemplate.update(user);  
    }  
  
    public void deleteUser(Long id) {  
        hibernateTemplate.delete(getUserById(id));  
    }  
}

Guess you like

Origin blog.csdn.net/q6115759/article/details/132580240