Data JPA-Crud Operation
Q) What is the difference b/w Sun/Oracle JPA and Data JPA?
A)Sun JPA is a Specification given to perform DB operations using ORM,But we should use one Vendor(3rd Party) ex: Hibernate with JPA.
Full code we should only write.
Data JPA reduces coding lines by using Pre-defined code.
-> Model class (we should write)
-> Persistency Configuration (give using properties files)
-> Operations code (write interfaces only).
S#1 application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/boot8pm
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=create
S#2 application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: root
url: jdbc:mysql://localhost:3306/boot8pm
username: root
jpa:
database-platform: org.hibernate.dialect.MySQL8Dialect
hibernate:
ddl-auto: create
show-sql: true
S#3 Model class with JPA Annotations
package in.nareshit.raghu.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table(name="stdtab")
public class Student {
@Id
@Column(name="sid")
private Integer stdId;
@Column(name="sname")
private String stdName;
@Column(name="sfee")
private Double stdFee;
}
S#4 Repository Interface
package in.nareshit.raghu.repo;
import org.springframework.data.repository.CrudRepository;
import in.nareshit.raghu.model.Student;
public interface StudentRepository
extends CrudRepository<Student, Integer> {
}
Note: CrudRepository<T,ID> is a pre-defined interface.[Here T= Model Class Name, ID=DataType of PrimaryKey variable.]
=> It provide all basic database operations methods ex: insert, update, delete and select.
=> For all these operations, we need not to define code (like Hibernate, JDBC code...)
S#5 Test class
package in.nareshit.raghu.runner;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import in.nareshit.raghu.model.Student;
import in.nareshit.raghu.repo.StudentRepository;
@Component
public class TestStudentOpr implements CommandLineRunner {
@Autowired
private StudentRepository repo;
public void run(String... args) throws Exception {
repo.save(new Student(101, "SYED MD", 580.0));
repo.save(new Student(102, "AMRIT", 480.0));
repo.save(new Student(103, "ANIL", 600.0));
repo.save(new Student(104, "SAM", 320.0)); //INSERT
repo.save(new Student(104, "SAM SANJU", 620.0));//UPDATE
repo.saveAll(
List.of(
new Student(105, "ABC", 800.0),
new Student(106, "XYZ", 900.0),
new Student(107, "MNO", 500.0)
)
);
System.out.println("############# findAll() #############");
Iterable all = repo.findAll();
all.forEach(System.out::println);
System.out.println("______________existsById(107)_______________");
boolean exist1 = repo.existsById(107);
boolean exist2 = repo.existsById(108);
System.out.println("Data exist => " + exist1 +", " + exist2);
System.out.println("------findById(108)--------");
Optional opt = repo.findById(108);
if(opt.isPresent()) {
Student s = opt.get();
System.out.println("Data Found=>" +s);
} else {
System.out.println("NO DATA");
}
System.out.println("**********findAllById()**************");
Iterable list = repo.findAllById(Arrays.asList(101,104,106,220,350,480));
Iterator itr = list.iterator();
while (itr.hasNext()) {
Student s = itr.next();
System.out.println(s);
}
System.out.println("Total rows " + repo.count());
System.out.println("****************** deleteById() ***********************");
repo.deleteById(103);
System.out.println("****************** delete() ***********************");
Student s = new Student();
s.setStdId(101);
repo.delete(s);
System.out.println("****************** delete() ***********************");
repo.deleteAll(
Arrays.asList(
new Student(101),
new Student(103),
new Student(105)
)
);
repo.deleteAll();
}
}
---------------------------------------------------------------------------------------------------
1. save(obj):obj
First it will read ID given by object,If ID is not present in DB then save method behaves like INSERT QUERY (persist)
else save method behaves like UPDATE QUERY (merge)
2. saveAll(Iterable entities)
This method is used to perform bulk INSERT/UPDATE.ie ex: execute 50 objects INSERT at a time.
3. findAll(): Iterable
This method is used to fetch all rows from DB table.
4. existsById(id):boolean
This method is used to check given ID exist in DB or not ? If exist then true, else then false.This method internally uses count() concept.
5. findById(id):Optional
This method is used to get one row data from DB using ID(PK).It reutns data in Optional format (JDK 1.8).It says check null condition and then read,
using methods like isPresent() , isEmpty()
6. findAllById(Iterable ids): Iterable
This method internally uses in operator. It takes list of ids as input and returns list of objects(rows matching) as output.
7. count():long
This method is used to find total no.of rows in given db table.SQL: select count(*) from tableName;
8.deleteById(id):void
Delete one row/object by id(PK) then we can use this method
repo.deleteById(103);
9. delete(obj):void (legacy app)
This method takes an object having PK(ID) value and performs onerow delete.
Student s = new Student();
s.setStdId(101);
repo.delete(s);
10. deleteAll(Iterable entities):void (leagcy app)
This method is used to delete multiple rows based on id one by one.But we need to pass object having PK value.
repo.deleteAll(
Arrays.asList(
new Student(101),
new Student(103),
new Student(105)
)
);
11. deleteAll() :
This method is used to delete all rows based on id one by one.
repo.deleteAll();
-------------Optional------------------------------- *)
Data in realtime applications may come from UI or Database.If no data exist then it is null.
If data is null and we try to perform operation then JVM throws NullPointerException
*) To void NPE, use code standard
if(data!=null)
data.methodCall();
else sysout("NO DATA");
=> but few developer may not follow above rule. So, java added a class name Optional to make above standard as must written code.
*) Now use methods isPresent() or isEmpty() before reading data
isPresent() -> value!=null
isEmpty() --> value==null
To read actual data method : get()
Q) What is the super type for Collection?
Q) What is the difference b/w forEach() method (in List) and enhanced for-each loop ?
No Comments Yet!!