A Database Management System (DBMS) is software used to store, manage, and retrieve data efficiently. Popular examples include MySQL, PostgreSQL, Oracle, MariaDB, and SQL Server. Traditionally, Java applications communicated with DBMSs using JDBC. As applications grew in complexity, developers needed a less repetitive, more object-focused approach, leading to the rise of Object-Relational Mapping (ORM) and eventually the Java Persistence API (JPA).
Applications should not connect as root. Create a dedicated MySQL user:
CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
GRANT CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, SELECT ON *.* TO 'sammy'@'localhost';
FLUSH PRIVILEGES;
This user now has sufficient privileges for typical CRUD operations.
JDBC is the low-level API used for direct SQL execution in Java. It gives full control but requires more boilerplate code.
import java.sql.*;
public class ConnectExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/dbms";
String user = "sammy";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to database!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
String query = "SELECT * FROM company";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
System.out.println(rs.getString(1) + " "
+ rs.getInt(2) + " "
+ rs.getString(3));
}
}
String insert = "INSERT INTO company VALUES ('BMW', 10, 'Germany')";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
stmt.executeUpdate(INSERT);
conn.COMMIT(); // or automatic IF AUTOCOMMIT=true
}
ORM is a programming technique that allows developers to interact with a relational database using Java objects.
Instead of manually writing SQL and processing ResultSet rows, the ORM handles:
Originally, Java developers used JDBC exclusively. As applications grew, developers wanted:
This led to early ORMs like Hibernate, and eventually the Java Persistence API (JPA), which standardized ORM behavior across Java.
JPA is not an ORM itselfβit is a specification. ORM frameworks like Hibernate, EclipseLink, and OpenJPA are implementations of the JPA standard.
In short:
This full example shows:
import jakarta.persistence.*;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int year;
// getters AND setters
}
EntityManager em = emf.createEntityManager();
em.getTransaction().BEGIN();
Student s = new Student();
s.setName("Alice");
s.setYear(2025);
em.persist(s);
em.getTransaction().COMMIT();
em.CLOSE();
Generated SQL under the hood:
INSERT INTO student (name, YEAR) VALUES (?, ?);
String jpql = "SELECT s FROM Student s WHERE s.year = :yr";
List list = em.createQuery(jpql, Student.class)
.setParameter("yr", 2025)
.getResultList();
em.getTransaction().BEGIN();
Student s = em.find(Student.class, 1L);
s.setName("Alicia"); // Hibernate detects this CHANGE automatically
em.getTransaction().COMMIT();
em.getTransaction().BEGIN();
Student s = em.find(Student.class, 1L);
em.remove(s);
em.getTransaction().COMMIT();
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private List orders = new ArrayList<>();
}
@Entity
public class Order {
@Id @GeneratedValue
private Long id;
private double total;
@ManyToOne
private User user;
}
public interface StudentRepository
extends JpaRepository {
List findByYear(int YEAR);
}
| Feature | JDBC | ORM | JPA |
|---|---|---|---|
| SQL Control | Full | Medium | Low |
| Boilerplate | High | Medium | Low |
| Mapping | No | Yes | Yes (standardized) |
| Best Use | High-performance, custom SQL | General applications | Large enterprise & Spring apps |