The Hibernate framework simplifies the process of interacting with the database in Java applications, involving the following concepts: entities (POJO represents database tables), sessions (database interaction), queries (retrieving data), mapping (association of classes and tables), transactions (Ensuring data consistency). Practical cases demonstrate the steps to create database tables, entity classes, Hibernate configuration files, and use the Hibernate API to perform basic database operations.
Hibernate framework study notes: from concept to practice
Introduction
Hibernate It is a lightweight, high-performance, open source Java persistence framework. It simplifies the process of managing and persisting objects to a database in Java applications.
Basic concepts
Practical case:
We will create a simple application to demonstrate the basic operation of Hibernate.
Setup
You will need:
Database Table
Create a database table named User
:
CREATE TABLE User ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, PRIMARY KEY (id) );
Entity Class
Create the entity class used to map the User
table User.java
:
@Entity @Table(name = "User") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String email; // Getters and setters }
Hibernate Configuration File
Create a Hibernate configuration file named hibernate.cfg.xml
:
<?xml version="1.0"?> <!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> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <mapping class="com.example.model.User" /> </session-factory> </hibernate-configuration>
Java Operation
Perform Hibernate operations in the Main.java
class:
public class Main { public static void main(String[] args) { // 创建SessionFactory SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); // 打开一个新的会话 Session session = sessionFactory.openSession(); // 开始一个事务 Transaction transaction = session.beginTransaction(); // 创建一个新的User实体 User user = new User(); user.setName("John"); user.setEmail("john@example.com"); // 保存实体 session.save(user); // 提交事务 transaction.commit(); // 关闭会话 session.close(); } }
The above is the detailed content of Hibernate framework study notes: from concept to practice. For more information, please follow other related articles on the PHP Chinese website!