Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Configuring and Mapping Entities


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.

1. Introduction to JPA and Entities

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.

2. Setting Up JPA in a Java Project

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>
        

3. Defining an Entity Class

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.

Example of an Entity Class

            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.

4. Configuring the Persistence Unit

To configure JPA, you need to define a persistence.xml file, which specifies the persistence unit and the connection to the database.

Example of persistence.xml

            <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.

5. Persisting Data Using JPA

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:

Example of Persisting an Entity

            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.

6. Querying Entities Using JPA

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:

Example of Querying Data

            import javax.persistence.EntityManager;
            import javax.persistence.EntityManagerFactory;
            import javax.persistence.Persistence;
            import javax.persistence.TypedQuery;
            import java.util.List;

            public class EmployeeService {

                public List getAllEmployees() {
                    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.

Conclusion

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.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java