Of course! Here is a comprehensive guide on how to insert data into a MySQL database using Java. We'll cover the two most common approaches:

- JDBC (Java Database Connectivity): The traditional, standard way. It's essential to understand.
- JPA (Java Persistence API) with Hibernate: The modern, object-relational mapping (ORM) approach, which is more abstract and often used in larger applications.
Prerequisites
-
MySQL Server: You need a running MySQL server.
-
Database and Table: Create a database and a table to insert data into.
-- Create a database CREATE DATABASE my_company; -- Use the database USE my_company; -- Create an 'employees' table CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, hire_date DATE NOT NULL ); -
MySQL Connector/J: You need the JDBC driver for MySQL.
- Download: Get the latest version from the MySQL Connector/J download page.
- Maven/Gradle: If you use a build tool, add the dependency. This is the recommended method.
Maven (
pom.xml):
(图片来源网络,侵删)<dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.33</version> <!-- Use the latest version --> </dependency>Gradle (
build.gradle):implementation 'com.mysql:mysql-connector-j:8.0.33' // Use the latest version
Method 1: Using JDBC (The Classic Approach)
This method involves writing raw SQL queries and managing database connections manually.
Step-by-Step Example
Let's create a JDBCInsertExample.java file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;
public class JDBCInsertExample {
// Database connection details
private static final String DB_URL = "jdbc:mysql://localhost:3306/my_company";
private static final String USER = "root"; // Your MySQL username
private static final String PASS = "your_password"; // Your MySQL password
public static void main(String[] args) {
// Employee data to insert
String firstName = "John";
String lastName = "Doe";
String email = "john.doe@example.com";
Date hireDate = Date.valueOf("2025-10-26"); // java.sql.Date
// The SQL INSERT statement with placeholders (?)
String insertSql = "INSERT INTO employees (first_name, last_name, email, hire_date) VALUES (?, ?, ?, ?)";
// Use try-with-resources to ensure the connection is closed automatically
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement pstmt = conn.prepareStatement(insertSql)) {
// Set the parameters for the prepared statement
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
pstmt.setString(3, email);
pstmt.setDate(4, hireDate);
// Execute the insert statement
int rowsAffected = pstmt.executeUpdate();
// Check the result
if (rowsAffected > 0) {
System.out.println(rowsAffected + " row(s) inserted successfully!");
}
} catch (SQLException e) {
System.err.println("Database error: " + e.getMessage());
e.printStackTrace();
}
}
}
Explanation of Key JDBC Concepts
DriverManager.getConnection(...): Establishes a connection to the database URL.PreparedStatement: This is the most important part for security and performance.- Security: It prevents SQL Injection attacks by separating the SQL command from the data.
- Performance: The database can pre-compile the SQL statement, making subsequent executions (if you were to loop and insert many records) much faster.
pstmt.set...(): You set the values for the placeholders () in the order they appear in the SQL string.setString(1, ...): Sets the first to a String value.setDate(4, ...): Sets the fourth to ajava.sql.Dateobject.
pstmt.executeUpdate(): Executes the SQL command. ForINSERT,UPDATE, orDELETEstatements, it returns an integer representing the number of affected rows.try-with-resources: Thetry (Connection ...; PreparedStatement ...)syntax ensures thatconn.close()andpstmt.close()are called automatically, even if an exception occurs. This prevents resource leaks.
Method 2: Using JPA with Hibernate (The ORM Approach)
This approach is more object-oriented. You define a Java class (an Entity) that maps to your database table, and Hibernate handles the SQL generation and database interaction for you.

Step 1: Add Dependencies
You'll need the Hibernate and JPA API dependencies.
Maven (pom.xml):
<!-- JPA API -->
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</groupId>
<version>3.1.0</version>
</dependency>
<!-- Hibernate Core (the JPA implementation) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</groupId>
<version>6.2.5.Final</version> <!-- Use the latest version -->
</dependency>
<!-- MySQL Connector/J (same as before) -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
Step 2: Configure Hibernate
Create a file named hibernate.cfg.xml in your src/main/resources directory.
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my_company?useSSL=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">your_password</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Show the generated SQL (for debugging) -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- Automatically update the database schema based on entities -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- List of entity classes -->
<mapping class="com.example.Employee"/>
</session-factory>
</hibernate-configuration>
Step 3: Create the Entity Class
Create a Java class that represents the employees table.
import jakarta.persistence.*;
import java.time.LocalDate;
@Entity // Marks this class as a JPA entity (maps to a database table)
@Table(name = "employees") // Specifies the table name in the database
public class Employee {
@Id // Marks this field as the primary key
@GeneratedValue(strategy = GenerationType.IDENTITY) // Auto-increment for the primary key
private int id;
@Column(name = "first_name", nullable = false, length = 50) // Maps to the 'first_name' column
private String firstName;
@Column(name = "last_name", nullable = false, length = 50)
private String lastName;
@Column(name = "email", nullable = false, unique = true, length = 100)
private String email;
@Column(name = "hire_date", nullable = false)
private java.sql.Date hireDate;
// Constructors, Getters, and Setters are required
public Employee() {}
public Employee(String firstName, String lastName, String email, java.sql.Date hireDate) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.hireDate = hireDate;
}
// Getters and Setters...
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public java.sql.Date getHireDate() { return hireDate; }
public void setHireDate(java.sql.Date hireDate) { this.hireDate = hireDate; }
}
Step 4: Write the Java Code to Insert
Now, you can write the code to save an Employee object.
import com.example.Employee; // Your entity class
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.sql.Date;
public class HibernateInsertExample {
public static void main(String[] args) {
// Create an EntityManagerFactory (this is a heavy object, create it once per application)
EntityManagerFactory emf = Persistence.createEntityManagerFactory("myCompanyPU");
// Create an EntityManager (this is a light object, create one per unit of work)
EntityManager em = emf.createEntityManager();
// Employee data
String firstName = "Jane";
String lastName = "Smith";
String email = "jane.smith@example.com";
Date hireDate = Date.valueOf("2025-10-27");
Employee employee = new Employee(firstName, lastName, email, hireDate);
try {
em.getTransaction().begin(); // Start a transaction
em.persist(employee); // The object is scheduled for insertion
em.getTransaction().commit(); // Commit the transaction to execute the insert
System.out.println("Employee inserted successfully! Generated ID: " + employee.getId());
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback(); // Rollback in case of an error
}
System.err.println("Error inserting employee: " + e.getMessage());
e.printStackTrace();
} finally {
em.close(); // Close the EntityManager
emf.close(); // Close the EntityManagerFactory
}
}
}
Comparison: JDBC vs. JPA/Hibernate
| Feature | JDBC | JPA/Hibernate |
|---|---|---|
| Abstraction | Low-level. You write SQL. | High-level. You work with Java objects. |
| SQL Control | Full control over every SQL statement. | SQL is generated automatically. Less control. |
| Performance | Can be more performant for simple, batch operations if tuned correctly. | Slight overhead due to object-relational mapping. |
| Development Speed | Slower. Requires writing and maintaining a lot of boilerplate code. | Faster. Reduces boilerplate code significantly. |
| Complexity | Simple for basic CRUD. Becomes complex with relationships, transactions, etc. | Manages complexity (relationships, caching, transactions) out of the box. |
| Best For | Simple scripts, performance-critical applications, or when you need fine-grained SQL control. | Most standard applications, especially those with complex object models. |
Recommendation:
- For small projects, simple scripts, or when you need maximum performance and control, JDBC is perfectly fine.
- For most applications, especially medium to large-scale enterprise applications, JPA with Hibernate is the industry standard and is highly recommended due to its productivity and maintainability.
