You are on page 1of 5

Spring Data JPA

================
It is java specification.
Jakarta Persistence API
Manages relational data in java applications.
To access and persist data between java object(POJO(plain old java object)/class)
and relational database.
it follows,Upon Object-relation Mapping(ORM)
it has runtime entityManger API
Responsible for processing queries and transactions on java objects against the
database.
It uses JPQL(java persistent Query language)
JPQL is platform -independent.
-----
JPA
Object relation metadata
jpa is not framework,it is concept any framework can implemented.
-----
Advantages
****
No need to write DDL/DML queries
we can map by using XML/annotations.
we no need to depend on any native SQL table.
complex expressions and filtering expressions are all handled via JPQL.
-----
jakarta persistence package
--
entityManger - it is iterface,it works for the query instance.
entity - persistent objects & stored as records in the database.
entityTransaction -it has one-to-one relationship with entityManger.
Query - get relation objects that meet the criteria.
----- JPA & Hibernate
---------------------
jpa-java specification for mapping relational data in java application. it is not a
framework
Hibernate is an ORM framework & this way data persistence is possible.
-
jpa - no implemented classes are provided.
Hibernate implemented classes are provided
--
jpa uses JPQL & platform independent query language
Hibernate uses HQL(Hibernate Query language)
---
jpa available in jakarta.persistence package
Hibernate available under org.Hibernate package
----
JPA implementation are Hibernate,EclipseLink etc
Hibernate is implementation of jpa
-----
in jpa, Persistence of data is handled by entityManger
in Hibernate, persistence of data is handledby session.
**********
Spring Boot provides starter dependency spring-boot-starter-data-jpa
to connect Spring Boot application with relational database efficiently.
This is the mandatory one
********
==============
@Entity
public class GeekUserRecord {
// Required attributes are given here. This will
// comprise as collection of columns of a table
@Id // For Primary key
private int id;
private String name;
private String email;
private String gender;
private int numberOfPosts;
// Getter and setter methods
// default constructor is mandatory to specify
}
-
// RestController = combination of the @Controller and the
// @ResponseBody It provides the response in the form of JSON
// or XML
@RestController
public class GeekUserController {
@Autowired private GeekUserService userService;
// To get all geekusers
@RequestMapping("/")
public List<GeekUserRecord> getAllUser()
{
return userService.getAllGeekUsers();
}

// To add a geekuser, this is needed


@RequestMapping(value = "/add-geekuser",
method = RequestMethod.POST)
public void
addUser(@RequestBody GeekUserRecord userRecord)
{
userService.addGeekUser(userRecord);
}
}
--
import com.gfg.model.GeekUserRecord;
import com.gfg.repository.GeekUserRepository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GeekUserService {
@Autowired
private GeekUserRepository geekUserRepository;
// for getting all the geekusers, we need to write this
// method and output is GeekUserRecord as a list,
public List<GeekUserRecord> getAllGeekUsers()
{
List<GeekUserRecord> geekUserRecords
= new ArrayList<>();
geekUserRepository.findAll().forEach(
geekUserRecords::add);
return geekUserRecords;
}

// While adding a geekuser, we need to save that


public void addGeekUser(GeekUserRecord userRecord)
{
geekUserRepository.save(userRecord);
}
}
---
public interface GeekUserRepository
extends CrudRepository<GeekUserRecord, String> {
}
----
// @PostMapping
// http://localhost:8080/add-geekuser
{
"id" : "091",
"name" : "geeka",
"email" : "geek@mgmail.com",
"gender" : "female",
"numberOfPosts" : 100
}
-----
application.properties (database configuration)
------
spring.datasource.url=jdbc:mysql://localhost:3306/user
spring.datasource.username=root
spring.datasource.password=Aayush
spring.jpa.hibernate.ddl-auto=update
***************************
Spring Data JPA – Find Records From MySQL
==
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;
String name;
User() {}
User(int id, String name)
{
this.id = id;
this.name = name;
}
}
--
import org.springframework.data.jpa.repository.JpaRepository;
interface UserRepo extends JpaRepository<User,Integer> {
}
---
package com.example.SpringBootApp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Optional;

@SpringBootApplication
public class SpringBootAppApplication implements CommandLineRunner {

@Autowired
UserRepo ob;
public static void main(String[] args) {
SpringApplication.run(SpringBootAppApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
User record=new User(1,"Aayush");
ob.save(record);
Optional<User> record=ob.findById(1);
record.stream().forEach(e->{
System.out.print(e.id+" "+e.name);
});

}
}
----
Spring Data JPA – Delete Records From MySQL
========
@SpringBootApplication
public class SpringBootAppApplication
implements CommandLineRunner {
@Autowired UserRepo ob;
public static void main(String[] args)
{
SpringApplication.run(SpringBootAppApplication.class, args);
}

@Override
public void run(String... args) throws Exception
{
// Inserting the data in the mysql table.
User first = new User(1, "Aayush");
// Deleting the record id is 1
ob.deleteById(1)
}
*************
spring-data-jpa-insert-data-in-mysql-table/
============
@SpringBootApplication
public class SpringBootAppApplication
implements CommandLineRunner {
@Autowired UserRepo ob;
public static void main(String[] args)
{
SpringApplication.run(SpringBootAppApplication.class, args);
}

@Override
public void run(String... args) throws Exception
{
// Inserting the data in the mysql table.
User first = new User(1, "Aayush");
// ob.save() method
ob.save(first);
}
}
************
spring-data-jpa-attributes-of-column-annotation-with-example
========
@Column(name = "Student_name" ,length = 30)
private String name;
------
@Column(columnDefinition = "varchar(22) default 'Aayush'")
private String name;
------
@Column(nullable=false)
private String name;

You might also like