Wednesday, 3 July 2019

JPA: @Id: Define primary key of an entity


@Id annotation is used to specify the primary key of an entity.

Can I apply @Id annotation on all the fields?
No, you can’t apply @Id annotation on all the fields. You can apply @Id annotation on one of the following fields.

a.   Any Java primitive type (byte, short, int, long, float, double, char, boolean)
b.   Any primitive wrapper type (Byte, Short, Integer, Long, Float, Double, Character, Boolean)
c.    String
d.   Java.util.Date
e.   Java.sql.Date
f.     Java.math.BigDecimal
g.   Java.math.BigInteger

You can apply @Id annotation on a property (or) on a getter method.

Example 1
public class Employee {

         @Id
         private int id;
        
}

Example 2
public class Employee {

         private int id;

         @Id
         public int getId() {
                  return id;
         }


Find the below working example.

Employee.java
package com.sample.myApp.entities;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name = "MY_EMPLOYEE")
public class Employee {

 private int id;
 private String firstName;
 private String lastName;

 @Id
 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;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}


persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
 xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
 <persistence-unit name="myPersistenceUnit"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

  <class>com.sample.myApp.entities.Employee</class>

  <properties>
   <property name="eclipselink.target-database" value="Derby" />
   <property name="javax.persistence.jdbc.driver"
    value="org.apache.derby.jdbc.ClientDriver" />
   <property name="javax.persistence.jdbc.url"
    value="jdbc:derby://localhost:1527/demoDatabase;create=true" />
   <property name="javax.persistence.jdbc.user" value="APP" />
   <property name="javax.persistence.jdbc.password" value="APP" />
   <property name="eclipselink.logging.level" value="INFO" />
   

   <property name="eclipselink.ddl-generation"
    value="drop-and-create-tables" />

   <property name="eclipselink.ddl-generation.output-mode"
    value="database" />
  </properties>

 </persistence-unit>
</persistence>


TestApp.java
package com.sample.myApp;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.sample.myApp.entities.Employee;

public class TestApp {

 public static void main(String args[]) {
  EntityManagerFactory emf = null;
  EntityManager em = null;

  try {
   emf = Persistence.createEntityManagerFactory("myPersistenceUnit");

   em = emf.createEntityManager();

   Employee emp = new Employee();
   emp.setFirstName("Krishna");
   emp.setLastName("Gurram");
   
   em.getTransaction().begin();
   em.persist(emp);
   em.getTransaction().commit();

   Query q = em.createQuery("select e from MY_EMPLOYEE e",
     Employee.class);
   List<Employee> emps = q.getResultList();
   for (Employee emp1 : emps) {
    System.out.println(emp1);
   }
  } finally {
   if (em != null && em.isOpen()) {
    em.close();
   }

   if (emf != null && emf.isOpen()) {
    emf.close();
   }
  }

 }

}


Project structure looks like below.


Run the application, you can able to see below messages in console.
[EL Info]: 2018-06-26 20:11:01.926--ServerSession(1978869058)--EclipseLink, version: Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f
[EL Info]: connection: 2018-06-26 20:11:02.192--ServerSession(1978869058)--/file:/C:/Users/krishna/java9/jpaDemo/target/classes/_myPersistenceUnit login successful
Employee [id=0, firstName=Krishna, lastName=Gurram]
[EL Info]: connection: 2018-06-26 20:11:02.562--ServerSession(1978869058)--/file:/C:/Users/krishna/java9/jpaDemo/target/classes/_myPersistenceUnit logout successful



From the DBVisualizer, you can confirm that the property ID is used as primary key.

Previous                                                    Next                                                    Home

No comments:

Post a Comment