Updated April 1, 2023
Introduction to JPA Annotations
In java technology it has some advanced programming features for secure and redundancy codes to save the memory and increase the performance of the application. Annotation is one of the feature that is it’s a metadata and is mainly used in the advanced java programming techniques like frameworks usages. Suppose we have used spring frameworks we will use the xml as a configuration purpose at same time we will use annotations also but JPA(Java persistence API) it has some annotations used for mapping the java objects into the backend like database tables it may be any of the dbs with the help of some ORM frameworks like Hibernate etc.
Syntax:
Given below is the basic syntax:
import javax.persistence.*;
@Entity //JPA Annotations
@Table(name=””) //JPA Annotations
class classname
{
@Id //JPA Annotations
@Column //JPA Annotations
----Some JPA annotations if needed for the programs-----
main method()
{
---some logic codes—
}
}
The above code is the basic steps and syntax while we used JPA annotations in the java applications.
How JPA Annotations are used in Java?
- JPA is the java api specifications used for relational database management in the applications if we create either desktop (java se edition) and Web(j2ee edition) applications based on the user requirements and also jpa used for reduce the complexity of the programs time complexity to increase the production growth.
- In JPA we define the db language called JPQL(Java Persistence Query Language) it is also known as object oriented query language syntax of the jpql. It is moreover similar to the sql but its directly called java objects instead of database tables.
- The jpa is specification purpose using that we can also implement any of the orm frameworks like hibernate for implementation purpose of the jpa entities.
- JPA annotations are not supported fully in the jdk if we use hibernate in jpa most probably @Id as the primary key for each table entity class @sequenceGenerator annotation is used to generate the primary keys automatically these are the some basic annotations for jpa in hibernate.
- We have mapped the database table using @Table and @SecondaryTable one table as the primary and another table as the secondary that is we have the entity relationship with the primary key and foreign key reference of the jpaobjects.
- Using these, we have three types of database relationship like @onetoone relationship, @onetomany relationship and @manytoone relationship. Each entity relationship has different features. It also focuses on different tables that are joined together so the joins is one of the main target for the database in jpa table per concrete class approach because the db table each column have different fields of each different types using inheritance concept. It will be approached for stored and retrieve the table datas especially distinct tables.
Examples of JPA Annotations
Given below are the examples:
Example #1
Controller Class:
package com.example.sample;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class controllerClass {
@Value("${welcome.message:User}")
private String message = "Hello World";
@RequestMapping("/")
public String welcome(Map<String, Object> model) {
model.put("message", this.message);
return "welcome";
}
}
Main Class:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class SamplesApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilderconfigure(SpringApplicationBuilder application) {
return application.sources(SamplesApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(SamplesApplication.class, args);
}
}
Welcome.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<style>
h1{
color:#0000FF;
}
h2{
color:#FF0000;
}
</style>
<title><h2>Welcome To MY Domain</h2></title>
</head>
<body>
<h1>Welcome USER</h1>
</body>
</html>
Output:
Example #2
Main Class:
package com.example.sample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import JPA.CustomerRepos;
import Model.CustomerModel;
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EnableJpaRepositories ("Model.CustomerRepos")
public class ExampleApplication {
private static final Logger log = LoggerFactory.getLogger(ExampleApplication.class);
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
@Bean
public CommandLineRunnerdemo(CustomerRepos repository) {
return (args) -> {
repository.save(new CustomerModel("siva", "raman"));
repository.save(new CustomerModel("arun", "kumar"));
repository.save(new CustomerModel("krishnan", "velu"));
repository.save(new CustomerModel("xxx", "eeee"));
repository.save(new CustomerModel("xxx2", "ffff"));
log.info("findAll():");
for (CustomerModelcustomer :repository.findAll()) {
log.info(customer.toString());
}
CustomerModel customer = repository.findById(1L);
log.info("findById(1L):");
log.info(customer.toString());
log.info("Customer found findByLastName('kumar'):");
repository.findByLastName("kumar").forEach(kumar -> {
log.info(kumar.toString());
});
};
}
}
Repository Class:
package JPA;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import Model.CustomerModel;
public interface CustomerRepos extends CrudRepository<CustomerModel, Long> {
List<CustomerModel>findByLastName(String lastName);
CustomerModelfindById(long id);
}
Model Class:
package Model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class CustomerModel {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String fName;
private String lName;
protected CustomerModel() {}
public CustomerModel(String fName, String lName) {
this.fName = fName;
this.lName = lName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, fName='%s', lName='%s']",
id, fName, lName);
}
public Long getId() {
return id;
}
public String getfName() {
return fName;
}
public String getlName() {
return lName;
}
}
Output:
Example #3
Model:
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="tests")
public class Model {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="id")
@OrderColumn(name="type")
private List<ans> a;
public intgetId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ans>getAns() {
return a;
}
public void setAns(List<ans> a) {
this.a = a;
}
}
Main Class:
import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreData {
public static void main(String[] args) {
StandardServiceRegistry s=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata m=new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory f=meta.getSessionFactoryBuilder().build();
Session sessions=factory.openSession();
Transaction t=session.beginTransaction();
Model m1=new Model();
m1.setAns("Welcome");
Model m2=new Model();
m2.setAns("To My Domain");
ArrayList<Model> lists=new ArrayList<Model>();
lists.add(m1);
ArrayList<Model>listss=new ArrayList<Model>();
listss.add(m2);
session.persist(lists);
session.persist(listss);
t.commit();
session.close();
System.out.println("successfull");
}
}
Output:
In the above three examples we use the jpa annotations we use jsp as the front end interact with the backend controller using jpa annotations with hibernate orm frameworks we have config the files using xml format.
Conclusion
In java we have used the persistent object called jpa it will come with the different ways and also in latest version of the java some jpa annotations are deprecated with new feature
Recommended Articles
This is a guide to JPA Annotations. Here we discuss the introduction to JPA annotations with respective examples for better understanding. You may also have a look at the following articles to learn more –