In Java, when working with databases, entities represent tables in the database. These entities are mapped to Java objects using Java Persistence API (JPA), which provides a way to define how objects relate to database tables. This article explains the process of configuring and mapping entities in Advanced Java.
The Java Persistence API (JPA) is a standard for managing relational data in Java applications. Entities are the building blocks of JPA. An entity class corresponds to a table in the database, and each instance of the entity class corresponds to a row in that table.
Entities are annotated with @Entity
, and you can map entity fields to columns in a database table using the @Column
annotation. The mapping defines how Java objects are stored in and retrieved from the database.
To configure JPA, you need to include necessary dependencies in your project. Here's an example of how to configure JPA in a pom.xml
file for Maven:
<dependency> <groupId>javax.persistence</groupId> <artifactId>javax.persistence-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.28.Final</version> </dependency>
Once JPA is configured, you can create entity classes. An entity class must be annotated with @Entity
, and it should have a primary key field annotated with @Id
.
import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Column; @Entity public class Employee { @Id private int id; @Column(name = "emp_name") private String name; @Column(name = "emp_salary") private double salary; // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }
In this example, the Employee
class is mapped to a database table with the same name (or a different name specified in the @Table
annotation). The class fields are mapped to columns in the table, and their names are specified using the @Column
annotation.
To configure JPA, you need to define a persistence.xml
file, which specifies the persistence unit and the connection to the database.
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="EmployeePU"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>com.example.Employee</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/employees"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="password"/> </properties> </persistence-unit> </persistence>
The persistence.xml
file configures the JPA provider (e.g., Hibernate) and sets properties like the database URL, username, and password.
To save an entity to the database, you need to use the EntityManager
to persist the entity object. Here’s an example of how to do this:
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class EmployeeService { public void saveEmployee(Employee employee) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(employee); em.getTransaction().commit(); em.close(); emf.close(); } }
In this example, an EntityManager
is used to persist an Employee
object to the database. The transaction is started, the entity is persisted, and the transaction is committed.
JPA allows you to query entities using the EntityManager
with JPQL (Java Persistence Query Language). Here’s an example of a query that retrieves all employees from the database:
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import java.util.List; public class EmployeeService { public ListgetAllEmployees() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeePU"); EntityManager em = emf.createEntityManager(); String jpql = "SELECT e FROM Employee e"; TypedQuery query = em.createQuery(jpql, Employee.class); List employees = query.getResultList(); em.close(); emf.close(); return employees; } }
In this example, we use JPQL to select all Employee
entities from the database. The TypedQuery
object is used to execute the query and return a list of employees.
In this article, we covered how to configure and map entities in Advanced Java using JPA. By defining entity classes, configuring the persistence unit, and using EntityManager
to persist and query entities, you can effectively work with relational databases in Java applications.