Zips & Tar

  • Creating zip
Zipping of fileszip backup.zip file1 file2 file3creates a zip containing the 3 files
Delete the original file after zipzip -m mybackup.zip file1Removes file1 after zipping it into backup.zip
Append a file in zip archivezip -u mybackup.zip file2Adds file2 to an existing zip mybackup.zip
Remove a file from a zip filezip -d mybackup.zip file1Removes file1 from mybackup.zip
Zipping a Directory recursivelyzip -r backupDir.zip dir1/ dir2/Zips the directories dir1 and dir2
  • Unzip commands
Basic unzipunzip mybackup.zip
Unzip content in a particular directoryunzip -d /home/directory/ mybackup.zipUnzips the content into /home/directory/ directory
List the contents of the zip fileunzip -l mybackup.ziplists the content of the zip file without extracting it
  • Gzip command

Compresses single file only. GZIP has a higher compression ration compared to normal zip.

Idea is to tar the required files and then gzip the single tar file.

GZIP removes the original file and creates a “.gz” file.

gzip myFile.txtcreates a myFile.txt.gz file and the original myFile.txt gets deleted.
gunzip myFile.txt.gzextracts the original file myFile.txt and myFile.txt.gz file gets removed.
  • Tar command

Stands for Tape Archive used for creating or extracting Archive files. Archive files are used to collect multiple data files together into single file for easier portability & storage.

Create a tar archivetar -cvf arch.tar *.javacreates a “arch.tar” archive file containing all the “.java” files present in the directory.
-c : Creates archive
-v : Verbose information
-f : given filename
Update existing tar filetar -rvf arch.tar *.htmladds all the “.html” files into existing tar “arch.tar”
Extract tar filetar -xvf arch.tarextracts the content of “arch.tar” into the current directory.
-x : Extract the archive
Extract tar file in specific directorytar -xvf arch.tar -C /home/directory/Extracts the content of the tar into directory “/home/directory/”
List tar content without extractiontar -tvf arch.tarLists the entire content of the “arch.tar” file

MAP mapping in JPA

A Map is an interface in which a unique key is associated with each value object. Thus, operations like search, update, delete are performed on the basis of key.

Map Mapping Example

In this example, we embed an object in an entity class and define it as a collection type Map.

  1. private Map<Integer,Address> map=new HashMap<Integer,Address>();  

This example contains the following steps: –

  • Create an entity class Employee.java under com.javatpoint.jpa package that contains employee id, name and embedded object (employee Address). The annotation @ElementCollection represents the embedded object.

Employee.java

  1. package com.javatpoint.jpa;  
  2. import java.util.*;  
  3.   
  4. import javax.persistence.*;  
  5. @Entity  
  6.   
  7. public class Employee {  
  8.   
  9.     @Id  
  10.     @GeneratedValue(strategy=GenerationType.AUTO)  
  11.     private int e_id;  
  12.     private String e_name;  
  13.       
  14.     @ElementCollection  
  15.     private Map<Integer,Address> map=new HashMap<Integer,Address>();  
  16.   
  17.       
  18.     public int getE_id() {  
  19.         return e_id;  
  20.     }  
  21.   
  22.     public void setE_id(int e_id) {  
  23.         this.e_id = e_id;  
  24.     }  
  25.   
  26.     public String getE_name() {  
  27.         return e_name;  
  28.     }  
  29.   
  30.     public void setE_name(String e_name) {  
  31.         this.e_name = e_name;  
  32.     }  
  33.   
  34.     public Map<Integer, Address> getMap() {  
  35.         return map;  
  36.     }  
  37.   
  38.     public void setMap(Map<Integer, Address> map) {  
  39.         this.map = map;  
  40.     }  
  41.   
  42.       
  43.       
  44. }  
  • Now, create a class of embedded object Address.java under com.javatpoint.jpa package. The annotation @Embeddable represents the embeddable object.

Address.java

  1. package com.javatpoint.jpa;  
  2. import javax.persistence.*;  
  3.   
  4. @Embeddable  
  5. public class Address {  
  6.   
  7.     private int e_pincode;  
  8.     private String e_city;  
  9.     private String e_state;  
  10.     public int getE_pincode() {  
  11.         return e_pincode;  
  12.     }  
  13.     public void setE_pincode(int e_pincode) {  
  14.         this.e_pincode = e_pincode;  
  15.     }  
  16.     public String getE_city() {  
  17.         return e_city;  
  18.     }  
  19.     public void setE_city(String e_city) {  
  20.         this.e_city = e_city;  
  21.     }  
  22.     public String getE_state() {  
  23.         return e_state;  
  24.     }  
  25.     public void setE_state(String e_state) {  
  26.         this.e_state = e_state;  
  27.     }  
  28.       
  29.       
  30.       
  31. }  
  • Now, map the entity class and other databases confiuguration in Persistence.xml file.

Persistence.xml

  1. <persistence>  
  2. <persistence-unit name=”Collection_Type”>  
  3.       
  4.      <class>com.javatpoint.jpa.Employee</class>  
  5.       <class>com.javatpoint.jpa.Address</class>  
  6.       
  7.   
  8.         
  9.      <properties>  
  10.       <property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver”/>  
  11.          <property name=”javax.persistence.jdbc.url” value=”jdbc:mysql://localhost:3306/collection_mapping”/>  
  12.          <property name=”javax.persistence.jdbc.user” value=”root”/>  
  13.          <property name=”javax.persistence.jdbc.password” value=””/>  
  14.          <property name=”eclipselink.logging.level” value=”SEVERE”/>  
  15.          <property name=”eclipselink.ddl-generation” value=”create-or-extend-tables”/>  
  16.       </properties>  
  17.       
  18.     </persistence-unit>  
  19. </persistence>  
  • Create a persistence class MapMapping.java under com.javatpoint.collection package to persist the entity object with data.

MapMapping.java

  1. package com.javatpoint.collection;  
  2. import javax.persistence.*;  
  3.   
  4.   
  5. import com.javatpoint.jpa.*;  
  6. public class ListMapping{  
  7.   
  8.     public static void main(String[] args) {  
  9.           
  10.         EntityManagerFactory emf=Persistence.createEntityManagerFactory(“Collection_Type”);  
  11.         EntityManager em=emf.createEntityManager();  
  12.           
  13.         em.getTransaction().begin();  
  14.           
  15.           
  16.   
  17.           
  18.         Address a1=new Address();  
  19.         a1.setE_pincode(201301);  
  20.         a1.setE_city(“Noida”);  
  21.         a1.setE_state(“Uttar Pradesh”);  
  22.           
  23.           
  24.           
  25.           
  26.           
  27.         Address a2=new Address();  
  28.         a2.setE_pincode(302001);  
  29.         a2.setE_city(“Jaipur”);  
  30.         a2.setE_state(“Rajasthan”);  
  31.           
  32.         Address a3=new Address();  
  33.         a3.setE_pincode(133301);  
  34.         a3.setE_city(“Chandigarh”);  
  35.         a3.setE_state(“Punjab”);  
  36.       
  37.         Address a4=new Address();  
  38.         a4.setE_pincode(80001);  
  39.         a4.setE_city(“Patna”);  
  40.         a4.setE_state(“Bihar”);  
  41.           
  42.           
  43.     Employee e1=new Employee();  
  44.     e1.setE_id(1);  
  45.     e1.setE_name(“Vijay”);  
  46.       
  47.       
  48.     Employee e2=new Employee();  
  49.     e2.setE_id(2);  
  50.     e2.setE_name(“Vijay”);  
  51.       
  52.     Employee e3=new Employee();  
  53.     e3.setE_id(3);  
  54.     e3.setE_name(“William”);  
  55.       
  56.     Employee e4=new Employee();  
  57.     e4.setE_id(4);  
  58.     e4.setE_name(“Rahul”);  
  59.       
  60.     e1.getMap().put(1, a1);  
  61.     e2.getMap().put(2, a2);  
  62.     e3.getMap().put(3, a3);  
  63.     e4.getMap().put(4, a4);  
  64.       
  65.     em.persist(e1);  
  66.     em.persist(e2);  
  67.     em.persist(e3);  
  68.     em.persist(e4);  
  69.       
  70.     em.getTransaction().commit();  
  71.       
  72.     em.close();  
  73.     emf.close();  
  74.           
  75.           
  76.           
  77.     }  
  78.       
  79. }  

Output:

After the execution of the program, the following tables are generated under MySQL workbench.

  • Employee table – This table contains the employee details. To fetch data, run select * from employee query in MySQL.
JPA Map Mapping
  • Employee_map table – This table represents the mapping between employee and address table. The data in the table is arranged in an unordered manner.To fetch data, run select * from employee_map query in MySQL.
JPA Map Mapping

Set Mapping in JPA

A Set is an interface that contains unique elements. These elements don’t maintain any order. A Set can be used when there is a requirement of retrieving unique elements in an unordered manner.

Set Mapping Example

In this example, we embed an object in an entity class and define it as a collection type List.

  1. private Set<Address> address=new HashSet<Address>();  

This example contains the following steps: –

  • Create an entity class Employee.java under com.javatpoint.jpa package that contains employee id, name and embedded object (employee Address). The annotation @ElementCollection represents the embedded object.

Employee.java

  1. package com.javatpoint.jpa;  
  2. import java.util.*;  
  3.   
  4. import javax.persistence.*;  
  5. @Entity  
  6.   
  7. public class Employee {  
  8.   
  9.     @Id  
  10.     @GeneratedValue(strategy=GenerationType.AUTO)  
  11.     private int e_id;  
  12.     private String e_name;  
  13.       
  14.     @ElementCollection  
  15.     private Set<Address> address=new HashSet<Address>();  
  16.   
  17.       
  18.     public int getE_id() {  
  19.         return e_id;  
  20.     }  
  21.   
  22.     public void setE_id(int e_id) {  
  23.         this.e_id = e_id;  
  24.     }  
  25.   
  26.     public String getE_name() {  
  27.         return e_name;  
  28.     }  
  29.   
  30.     public void setE_name(String e_name) {  
  31.         this.e_name = e_name;  
  32.     }  
  33.   
  34.     public Set<Address> getAddress() {  
  35.         return address;  
  36.     }  
  37.   
  38.     public void setAddress(Set<Address> address) {  
  39.         this.address = address;  
  40.     }  
  41.   
  42.       
  43. }  
  • Now, create a class of embedded object Address.java under com.javatpoint.jpa package. The annotation @Embeddable represents the embeddable object.

Address.java

  1. package com.javatpoint.jpa;  
  2. import javax.persistence.*;  
  3.   
  4. @Embeddable  
  5. public class Address {  
  6.   
  7.     private int e_pincode;  
  8.     private String e_city;  
  9.     private String e_state;  
  10.     public int getE_pincode() {  
  11.         return e_pincode;  
  12.     }  
  13.     public void setE_pincode(int e_pincode) {  
  14.         this.e_pincode = e_pincode;  
  15.     }  
  16.     public String getE_city() {  
  17.         return e_city;  
  18.     }  
  19.     public void setE_city(String e_city) {  
  20.         this.e_city = e_city;  
  21.     }  
  22.     public String getE_state() {  
  23.         return e_state;  
  24.     }  
  25.     public void setE_state(String e_state) {  
  26.         this.e_state = e_state;  
  27.     }  
  28.       
  29.       
  30.       
  31. }  
  • Now, map the entity class and other databases confiuguration in Persistence.xml file.

Persistence.xml

  1. <persistence>  
  2. <persistence-unit name=”Collection_Type”>  
  3.       
  4.     <class>com.javatpoint.jpa.Employee</class>  
  5. <class>com.javatpoint.jpa.Address</class>  
  6.   
  7.   
  8.   
  9. <properties>  
  10. <property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver”/>  
  11. <property name=”javax.persistence.jdbc.url” value=”jdbc:mysql://localhost:3306/collection_mapping”/>  
  12. <property name=”javax.persistence.jdbc.user” value=”root”/>  
  13. <property name=”javax.persistence.jdbc.password” value=””/>  
  14. <property name=”eclipselink.logging.level” value=”SEVERE”/>  
  15. <property name=”eclipselink.ddl-generation” value=”create-or-extend-tables”/>  
  16. </properties>  
  17.       
  18.     </persistence-unit>  
  19. </persistence>  
  • Create a persistence class ListMapping.java under com.javatpoint.collection package to persist the entity object with data.

SetMapping.java

  1. package com.javatpoint.collection;  
  2. import javax.persistence.*;  
  3.   
  4.   
  5. import com.javatpoint.jpa.*;  
  6. public class SetMapping{  
  7.   
  8.     public static void main(String[] args) {  
  9.           
  10.         EntityManagerFactory emf=Persistence.createEntityManagerFactory(“Collection_Type”);  
  11.         EntityManager em=emf.createEntityManager();  
  12.           
  13.         em.getTransaction().begin();  
  14.           
  15.           
  16.   
  17.           
  18.         Address a1=new Address();  
  19.         a1.setE_pincode(201301);  
  20.         a1.setE_city(“Noida”);  
  21.         a1.setE_state(“Uttar Pradesh”);  
  22.           
  23.           
  24.           
  25.           
  26.           
  27.         Address a2=new Address();  
  28.         a2.setE_pincode(302001);  
  29.         a2.setE_city(“Jaipur”);  
  30.         a2.setE_state(“Rajasthan”);  
  31.           
  32.         Address a3=new Address();  
  33.         a3.setE_pincode(133301);  
  34.         a3.setE_city(“Chandigarh”);  
  35.         a3.setE_state(“Punjab”);  
  36.       
  37.         Address a4=new Address();  
  38.         a4.setE_pincode(80001);  
  39.         a4.setE_city(“Patna”);  
  40.         a4.setE_state(“Bihar”);  
  41.           
  42.           
  43.     Employee e1=new Employee();  
  44.     e1.setE_id(1);  
  45.     e1.setE_name(“Vijay”);  
  46.       
  47.       
  48.     Employee e2=new Employee();  
  49.     e2.setE_id(2);  
  50.     e2.setE_name(“Vijay”);  
  51.       
  52.     Employee e3=new Employee();  
  53.     e3.setE_id(3);  
  54.     e3.setE_name(“William”);  
  55.       
  56.     Employee e4=new Employee();  
  57.     e4.setE_id(4);  
  58.     e4.setE_name(“Rahul”);  
  59.       
  60.     e1.getAddress().add(a1);  
  61.     e2.getAddress().add(a2);  
  62.     e3.getAddress().add(a3);  
  63.     e4.getAddress().add(a4);  
  64.       
  65.     em.persist(e1);  
  66.     em.persist(e2);  
  67.     em.persist(e3);  
  68.     em.persist(e4);  
  69.       
  70.     em.getTransaction().commit();  
  71.       
  72.     em.close();  
  73.     emf.close();  
  74.           
  75.           
  76.           
  77.     }  
  78.       
  79. }  

Output:

After the execution of the program, the following tables are generated under MySQL workbench.

  • Employee table – This table contains the employee details. To fetch data, run select * from employee query in MySQL.
JPA Set Mapping
  • Employee_address table – This table represents the mapping between employee and address table. The data in the table is arranged in an unordered manner.To fetch data, run select * from employee_address query in MySQL.
JPA Set Mapping

List Mapping in JPA

A List is an interface which is used to insert and delete elements on the basis of index. It can be used when there is a requirement of retrieving elements in a user-defined order.

List Mapping Example

In this example, we embed an object in an entity class and define it as a collection type List.

  1. private List<Address> address=new ArrayList<Address>();  

This example contains the following steps: –

  • Create an entity class Employee.java under com.javatpoint.jpa package that contains employee id, name and embedded object (employee Address). The annotation @ElementCollection represents the embedded object.

Employee.java

  1. package com.javatpoint.jpa;  
  2. import java.util.*;  
  3.   
  4. import javax.persistence.*;  
  5. @Entity  
  6.   
  7. public class Employee {  
  8.   
  9.     @Id  
  10.     @GeneratedValue(strategy=GenerationType.AUTO)  
  11.     private int e_id;  
  12.     private String e_name;  
  13.       
  14.     @ElementCollection  
  15.     private List<Address> address=new ArrayList<Address>();  
  16.   
  17.       
  18.     public int getE_id() {  
  19.         return e_id;  
  20.     }  
  21.   
  22.     public void setE_id(int e_id) {  
  23.         this.e_id = e_id;  
  24.     }  
  25.   
  26.     public String getE_name() {  
  27.         return e_name;  
  28.     }  
  29.   
  30.     public void setE_name(String e_name) {  
  31.         this.e_name = e_name;  
  32.     }  
  33.   
  34.     public List<Address> getAddress() {  
  35.         return address;  
  36.     }  
  37.   
  38.     public void setAddress(List<Address> address) {  
  39.         this.address = address;  
  40.     }  
  41.   
  42.       
  43. }  
  • Now, create a class of embedded object Address.java under com.javatpoint.jpa package. The annotation @Embeddable represents the embeddable object.

Address.java

  1. package com.javatpoint.jpa;  
  2. import javax.persistence.*;  
  3.   
  4. @Embeddable  
  5. public class Address {  
  6.   
  7.     private int e_pincode;  
  8.     private String e_city;  
  9.     private String e_state;  
  10.     public int getE_pincode() {  
  11.         return e_pincode;  
  12.     }  
  13.     public void setE_pincode(int e_pincode) {  
  14.         this.e_pincode = e_pincode;  
  15.     }  
  16.     public String getE_city() {  
  17.         return e_city;  
  18.     }  
  19.     public void setE_city(String e_city) {  
  20.         this.e_city = e_city;  
  21.     }  
  22.     public String getE_state() {  
  23.         return e_state;  
  24.     }  
  25.     public void setE_state(String e_state) {  
  26.         this.e_state = e_state;  
  27.     }  
  28.       
  29.       
  30.       
  31. }  
  • Now, map the entity class and other databases confiuguration in Persistence.xml file.

Persistence.xml

  1. <persistence>  
  2. <persistence-unit name=”Collection_Type”>  
  3.       
  4.     <class>com.javatpoint.jpa.Employee</class>  
  5. <class>com.javatpoint.jpa.Address</class>  
  6.   
  7.   
  8.   
  9. <properties>  
  10. <property name=”javax.persistence.jdbc.driver” value=”com.mysql.jdbc.Driver”/>  
  11. <property name=”javax.persistence.jdbc.url” value=”jdbc:mysql://localhost:3306/collection_mapping”/>  
  12. <property name=”javax.persistence.jdbc.user” value=”root”/>  
  13. <property name=”javax.persistence.jdbc.password” value=””/>  
  14. <property name=”eclipselink.logging.level” value=”SEVERE”/>  
  15. <property name=”eclipselink.ddl-generation” value=”create-or-extend-tables”/>  
  16. </properties>  
  17.       
  18.     </persistence-unit>  
  19. </persistence>  
  • Create a persistence class ListMapping.java under com.javatpoint.collection package to persist the entity object with data.

ListMapping.java

  1. package com.javatpoint.collection;  
  2. import javax.persistence.*;  
  3.   
  4.   
  5. import com.javatpoint.jpa.*;  
  6. public class ListMapping{  
  7.   
  8.     public static void main(String[] args) {  
  9.           
  10.         EntityManagerFactory emf=Persistence.createEntityManagerFactory(“Collection_Type”);  
  11.         EntityManager em=emf.createEntityManager();  
  12.           
  13.         em.getTransaction().begin();  
  14.           
  15.           
  16.   
  17.           
  18.         Address a1=new Address();  
  19.         a1.setE_pincode(201301);  
  20.         a1.setE_city(“Noida”);  
  21.         a1.setE_state(“Uttar Pradesh”);  
  22.           
  23.           
  24.           
  25.           
  26.           
  27.         Address a2=new Address();  
  28.         a2.setE_pincode(302001);  
  29.         a2.setE_city(“Jaipur”);  
  30.         a2.setE_state(“Rajasthan”);  
  31.           
  32.       
  33.           
  34.     Employee e1=new Employee();  
  35.     e1.setE_id(1);  
  36.     e1.setE_name(“Vijay”);  
  37.     e1.getAddress().add(a1);  
  38.       
  39.     Employee e2=new Employee();  
  40.     e2.setE_id(2);  
  41.     e2.setE_name(“John”);  
  42.     e2.getAddress().add(a2);  
  43.       
  44.     em.persist(e1);  
  45.     em.persist(e2);  
  46.       
  47.     em.getTransaction().commit();  
  48.       
  49.     em.close();  
  50.     emf.close();  
  51.           
  52.           
  53.           
  54.     }  
  55.       
  56. }  

Output:

After the execution of the program, the following table are generated under MySQL workbench.

  • Employee table – This table contains the employee details. To fetch data, run select * from employee query in MySQL.
JPA List Mapping
  • Employee_address table – This table represents the mapping between employee and address table. To fetch data, run select * from employee_address query in MySQL.
JPA List Mapping

Collection Mapping in JPA

A Collection is a java framework that groups multiple objects into a single unit. It is used to store, retrieve and manipulate the aggregate data.

In JPA, we can persist the object of wrapper classes and String using collections. JPA allows three kinds of objects to store in mapping collections – Basic Types, Entities and Embeddables.

Collection Types

On the basis of requirement, we can use different type of collections to persist the objects.

  • List
  • Set
  • Map
JPA Collection Mapping

The java.util package contains all the classes and interfaces of collection framework.

Example of Find, insert, Update, Delete in JPA

SQL

create table emp(
	eid int,
	ename varchar(40),
	elanguage  varchar(40)
);
insert into emp values (1,'Tyson','Java');
insert into emp values (2,'Justin','Python');
insert into emp values (3,'Martin','C++');

commit;

persistence.xml (/src/main/resources/META-INF/persistence.xml)

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             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="pu" transaction-type="RESOURCE_LOCAL">
    	<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    	<class>com.demo.Emp</class>
        <properties>
           <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
           <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mysql"/>
           <property name="javax.persistence.jdbc.user" value="tyson"/>
           <property name="javax.persistence.jdbc.password" value="tyson"/>
           
           <property name = "hibernate.show_sql" value = "true" />
           <property name = "hibernate.format_sql" value = "true" />
           <property name = "hibernate.hbm2ddl.auto" value = "none" />
           <property name = "hibernate.dilect" value = "org.hibernate.dialect.MySQLDialect" />
        </properties>
        
    </persistence-unit>

</persistence>

Emp.java

package com.demo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="emp")
public class Emp {
	@Id
	@Column(name="eid")
	private int eid;
	
	@Column(name="ename",nullable=false,length=40)
	private String ename;
	
	@Column(name="elanguage",nullable=false,length=40)
	private String elanguage;
	
	public int getEid() {
		return eid;
	}
	public void setEid(int eid) {
		this.eid = eid;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public String getElanguage() {
		return elanguage;
	}
	public void setElanguage(String elanguage) {
		this.elanguage = elanguage;
	}
	@Override
	public String toString() {
		return "Emp [eid=" + eid + ", ename=" + ename + ", elanguage=" + elanguage + "]";
	}
}

App.java

package com.demo;

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

public class App {
	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");
		EntityManager em = emf.createEntityManager();
		
		//findExample - select a specific row
		printEmployee(em);
		
		//insert a single row - persist
		createEmployee(em,4,"Fade","C#");
		
		//update a single row 
		updateEmployee(em,"Jade");
		
		//only single delete
		deleteEmployee(em,3);
		
		em.close();
		emf.close();
		
	}
	
	private static void printEmployee(EntityManager em) {
		Emp e = em.find(Emp.class, 3);
		System.out.println(e);
	}
	
	private static void createEmployee(EntityManager em,int id,String name,String language) {
		Emp e = new Emp();
		e.setEid(id);
		e.setEname(name);
		e.setElanguage(language);
		
		em.getTransaction().begin();
		em.persist(e);
		em.getTransaction().commit();
		
	}
	
	private static void updateEmployee(EntityManager em, String name) {
		Emp e = em.find(Emp.class, 3);
		System.out.println(e.toString());
		em.getTransaction().begin();
		e.setEname(name);
		em.getTransaction().commit();
		System.out.println(e.toString());
	}
	
	private static void deleteEmployee(EntityManager em, int id) {
		em.getTransaction().begin(); 
		Emp e = em.find(Emp.class, id);
		em.remove(e);
		em.getTransaction().commit();  
	}
}

JPA persistance.xml file

sample: persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             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="pu" transaction-type="RESOURCE_LOCAL">
    	<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
           <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
           <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mysql"/>
           <property name="javax.persistence.jdbc.user" value="tyson"/>
           <property name="javax.persistence.jdbc.password" value="tyson"/>
           
           <property name = "hibernate.show_sql" value = "true" />
           <property name = "hibernate.format_sql" value = "true" />
           <property name = "hibernate.hbm2ddl.auto" value = "none" />
           <property name = "hibernate.dilect" value = "org.hibernate.dialect.MySQLDialect" />
        </properties>
    </persistence-unit>
</persistence>
  • persistence-unit
    • unit for each db connection
    • name
      • Name to the connection
    • transaction-type
      • RESOURCE_LOCAL
        • For Standalone projects
      • JTA (Default)
        • For JavaEE projects
  • provider
    • Name of the ORM framework you are using, in our case it is Hibernate
  • class
    • Name of the Entities listed here
  • Properties
    • javax.persistence.jdbc.driver
      • JDCB Driver name
    • javax.persistence.jdbc.url
      • Connection URL
    • javax.persistence.jdbc.user
      • Username of DB
    • javax.persistence.jdbc.password
      • Password of DB
    • hibernate.show_sql
      • prints SQL executed
    • hibernate.format_sql
      • formats the SQL
    • hibernate.hbm2ddl.auto
      • validate: validate the schema, makes no changes to the database.
      • update: update the schema.
      • create: creates the schema, destroying previous data.
      • create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.
      • none: does nothing with the schema, makes no changes to the database

Reference :

JPA Annotation

AnnotationDescription
@EntityDeclares the class as an entity or a table.
@TableDeclares table name.
@BasicSpecifies non-constraint fields explicitly.
@EmbeddedSpecifies the properties of class or an entity whose value is an instance of an embeddable class.
@IdSpecifies the property, use for identity (primary key of a table) of the class.
@GeneratedValueSpecifies how the identity attribute can be initialized such as automatic, manual, or value taken from a sequence table.
@TransientSpecifies the property that is not persistent, i.e., the value is never stored in the database.
@ColumnSpecifies the column attribute for the persistence property.
@SequenceGeneratorSpecifies the value for the property that is specified in the @GeneratedValue annotation. It creates a sequence.
@TableGeneratorSpecifies the value generator for the property specified in the @GeneratedValue annotation. It creates a table for value generation.
@AccessTypeThis type of annotation is used to set the access type. If you set @AccessType(FIELD), then access occurs Field wise. If you set @AccessType(PROPERTY), then access occurs Property wise.
@JoinColumnSpecifies an entity association or entity collection. This is used in many- to-one and one-to-many associations.
@UniqueConstraintSpecifies the fields and the unique constraints for the primary or the secondary table.
@ColumnResultReferences the name of a column in the SQL query using select clause.
@ManyToManyDefines a many-to-many relationship between the join Tables.
@ManyToOneDefines a many-to-one relationship between the join Tables.
@OneToManyDefines a one-to-many relationship between the join Tables.
@OneToOneDefines a one-to-one relationship between the join Tables.
@NamedQueriesspecifies list of named queries.
@NamedQuerySpecifies a Query using static name.

Architecture of JPA

Java Persistence API is a source to store business entities as relational entities. It shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations.

Class Level Architecture

The following image shows the class level architecture of JPA. It shows the core classes and interfaces of JPA.

JPA Class Level Architecture

The following table describes each of the units shown in the above architecture.

UnitsDescription
EntityManagerFactoryThis is a factory class of EntityManager. It creates and manages multiple EntityManager instances.
EntityManagerIt is an Interface, it manages the persistence operations on objects. It works like factory for Query instance.
EntityEntities are the persistence objects, stores as records in the database.
EntityTransactionIt has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.
PersistenceThis class contain static methods to obtain EntityManagerFactory instance.
QueryThis interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

The above classes and interfaces are used for storing entities into a database as a record. They help programmers by reducing their efforts to write codes for storing data into a database so that they can concentrate on more important activities such as writing codes for mapping the classes with database tables.

JPA Class Relationships

In the above architecture, the relations between the classes and interfaces belong to the javax.persistence package. The following diagram shows the relationship between them.

JPA Class Relationships
  • The relationship between EntityManagerFactory and EntityManager is one-to-many. It is a factory class to EntityManager instances.
  • The relationship between EntityManager and EntityTransaction is one-to-one. For each EntityManager operation, there is an EntityTransaction instance.
  • The relationship between EntityManager and Query is one-to-many. Many number of queries can execute using one EntityManager instance.
  • The relationship between EntityManager and Entity is one-to-many. One EntityManager instance can manage multiple Entities.

What is JPA

The Java Persistence API (JPA) is a specification of Java. It is used to persist data between Java object and relational database. JPA acts as a bridge between object-oriented domain models and relational database systems.

As JPA is just a specification, it doesn’t perform any operation by itself. It requires an implementation. So, ORM tools like Hibernate, TopLink and iBatis implements JPA specifications for data persistence.

JPA Versions

The first version of Java Persistenece API, JPA 1.0 was released in 2006 as a part of EJB 3.0 specification.

Following are the other development versions released under JPA specification: –

  • JPA 2.0 – This version was released in the last of 2009. Following are the important features of this version: –
    • It supports validation.
    • It expands the functionality of object-relational mapping.
    • It shares the object of cache support.
  • JPA 2.1 – The JPA 2.1 was released in 2013 with the following features: –
    • It allows fetching of objects.
    • It provides support for criteria update/delete.
    • It generates schema.
  • JPA 2.2 – The JPA 2.2 was released as a development of maintainenece in 2017. Some of its important feature are: –
    • It supports Java 8 Date and Time.
    • It provides @Repeatable annotation that can be used when we want to apply the same annotations to a declaration or type use.
    • It allows JPA annotation to be used in meta-annotations.
    • It provides an ability to stream a query result.

JPA Providers

JPA is an open source API, therefore various enterprise vendors such as Oracle, Redhat, Eclipse, etc. provide new products by adding the JPA persistence flavor in them. Some of these products include:

Hibernate, Eclipselink, Toplink, Spring Data JPA, etc.