Loading

Quipoin Menu

Learn • Practice • Grow

spring / JPA and Hibernate Introduction
tutorial

JPA and Hibernate Introduction

Imagine you have a library with books. You need to keep track of each book's title, author, and location. You could write everything in a notebook (like JDBC), but it would be messy. Instead, you use a catalog system where each book has a card with all its details (like JPA).

JPA (Java Persistence API) is a specification – a set of rules – for mapping Java objects to database tables. Hibernate is the most popular implementation of JPA (like a brand that follows those rules).

ORM (Object-Relational Mapping) is the concept of mapping Java objects to database tables. Each table row becomes a Java object, and each column becomes a field.

Here is a simple JPA entity:


@Entity
@Table(name = "students")
public class Student {

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

@Column(name = "student_name", nullable = false)
private String name;

@Column(unique = true)
private String email;

private int age;

// constructors, getters, setters
}

Key JPA Annotations:
  • @Entity – marks class as a JPA entity (maps to a table).
  • @Table – specifies table name (optional, defaults to class name).
  • @Id – marks the primary key.
  • @GeneratedValue – how the ID is generated (AUTO, IDENTITY, SEQUENCE).
  • @Column – column details (name, nullable, unique, length).

To use JPA with Spring, you need to configure EntityManagerFactory:


@Configuration
@EnableTransactionManagement
public class JpaConfig {

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.example.entity");

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL8Dialect");
vendorAdapter.setShowSql(true);
em.setJpaVendorAdapter(vendorAdapter);

return em;
}

@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
}
Two Minute Drill
  • JPA is a specification for mapping Java objects to database tables.
  • Hibernate is the most popular JPA implementation.
  • ORM = Object-Relational Mapping – the concept behind JPA.
  • Use @Entity to mark a class as a database table.
  • @Id marks the primary key, @Column defines column properties.

Need more clarification?

Drop us an email at career@quipoinfotech.com