Data Jpa Running Notes
Data Jpa Running Notes
=> Using ORM we can represent our data in the form objects.
=> The java class which is mapped to db table is called as Entity class
==========
DB Setup
==========
DB Server : MySQL
=> Create DB connection in workbench and execute below queries to create database.
show databases;
create database sbms36;
use sbms36;
show tables;
==================================
Data JPA Application development
==================================
a) CrudRepository
b) JpaRepository (more features)
5) Get repository bean obj and test repository methods using start class.
-------------------------------------------------------------------------
spring.datasource.username=root
spring.datasource.password=ashokit@123
spring.datasource.url=jdbc:mysql://localhost:3306/sbms36
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
--------------------------------------------------------------------------
@Entity
public class Book {
@Id
private Integer bookId;
private String bookName;
private Double bookPrice;
}
-------------------------------------------------------------------
public interface BookRepository extends CrudRepository<Book, Integer> {
}
-------------------------------------------------------------------
@SpringBootApplication
public class Application {
bookRepo.save(b); // UPSERT
}
-------------------------------------------------------------------
-------------------------------------------------------------------
========================
CrudRepository methods
========================
-------------------------------------------------------------------------
@Service
public class EmployeeService {
emp.setEmpId(101);
emp.setEmpName("Charles");
emp.setEmpGender("Male");
emp.setEmpDept("Sales");
emp.setEmpSalary(18000.00);
empRepo.save(emp);
}
empRepo.saveAll(empsList);
}
}
================
findBy Methods
================
findById ( ) - pk
findAllById( ) - pks
================================================================
Q) How to retrieve records based on non-primary column values ?
================================================================
=> Using findBy methods we can retrieve data from table
=> When we write findBy methods, jpa will construct query based on method name.
Syntax : findByXXX(params)
findByEmpDept
=================
Custom Queries
==================
=> We can write our own query and we can execute it using jpa
@Query("query-goes-here")
public Employee getEmps();
1) SQL Queries
2) HQL Queries
// SQL queries will use table name and column names in the query
// HQL queries will use Entity class name and variable names in the query
From Employee
==============EmpRepository.java=========================================
@Query("from Employee")
public List<Employee> getAllEmpRecords();
}
=======================================================
@Service
public class EmployeeService {
emp.setEmpId(101);
emp.setEmpName("Charles");
emp.setEmpGender("Male");
emp.setEmpDept("Sales");
emp.setEmpSalary(18000.00);
empRepo.save(emp);
}
empRepo.saveAll(empsList);
}
}
=============================================================
============================================================
public interface EmployeeRepo extends CrudRepository<Employee, Integer> {
@Query("from Employee")
public List<Employee> getAllEmps();
@Transactional
@Modifying
@Query("delete from Employee where empId=:eid")
public void deleteEmp(Integer eid);
}
============================================================
====================
Today's Assignment
====================
3) Write a custom query to retrieve emp_name and emp_dept using Custom HQL query.
1) Using jpa provided pre-defined methods we can peform Both select & non-select
operations
=======================================================
1000 db tables
2) JpaRepository
==========================================================
emp.setEmpDept("Marketing");
emp.setEmpGender("Male");
emp.setEmpName("Ruther");
Example<Employee> of = Example.of(emp);
List<Employee> findAll = empRepo.findAll(of);
==============
Timestamping
==============
contact_us_leads
contact_id PK
name
email
phno
msg
created_date =====> @CreationTimestamp
updated_date =====> @UpdateTimestamp
========================================================
@Entity
@Table(name = "contact_us_leads")
public class ContactUsEntity {
@Id
private Integer cid;
private String cname;
private String cemail;
private String cphno;
@CreationTimestamp
@Column(name = "created_date", updatable = false)
private LocalDateTime createdDate;
@UpdateTimestamp
@Column(name = "updated_date", insertable = false)
private LocalDateTime updatedDate;
=============================================================
===========
Generators
===========
=> Generators are used to generate the value for primary key column
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer cid;
=> Identity generator will use auto_increment to populate primary key column value
=> sequence generator will use db sequence to populate primary key column value
=> table generator will use seperate table to maintain primary column values.
=> If we want to generate alphanumeric data for PK column then we can create our
own generator (Custom Generator).
TCS1
TCS2
TCS3
.
.
.
=====================
Today's Assignment
===================
1) Insert record into table using custom query
======================
Composite Primary Key
=======================
----------------------------------------------
@Embeddable
public class BookPk {
}
----------------------------------------------
@Entity
@Table(name = "BOOKS_INFO_TBL")
public class Book {
@EmbeddedId
private BookPk bookPk;
}
----------------------------------------------------------------
public interface BookRepo extends JpaRepository<Book, BookPk>{
-----------------------------------------------------------------
@Service
public class BookService {
@Autowired
private BookRepo repo;
//service.saveBook();
service.getBook();
}
}
----------------------------------------------------------
1) @Entity
2) @Table
3) @Id
4) @Column
5) @GeneratedValue
6) @GenericGenerator
7) @CreationTimestamp
8) @UpdateTimestamp
9) @Embeddable
10) @EmbeddedId
1) @Component
2) @Service
3) @Repository
4) @Configuration
5) @Bean
6) @Primary
7) @Autowired
8) @Qualifier
9) @Scope
10) @ComponentScan
11) @SpringBootApplication
12) @PostConstruct
13) @PreDestroy
=========================================
How to work with Embedded Database (h2)
==========================================
======================================
Spring Boot app with h2 db - example
======================================
a) jpa-starter
b) h2
c) web-starter
spring.datasource.username=ashokit
spring.datasource.password=ashokit
spring.datasource.url=jdbc:h2:mem:test
spring.datasource.driverClassName=org.h2.Driver
spring.h2.console.enabled=true
spring.jpa.show-sql=true
server.port=9090
URL : http://localhost:port/h2-console
==================
Spring Profiles
==================
Application Environments
Local Env : Where we will develop code & perform unit test
1) What is Environment
- data source
- kafka properties
- redis properties
- payment gateway properties
- Third party apis endpoint urls
Note: For every env we will create one profile with env specific configuration
application.properties (default)
application-dev.properties
application-sit.properties
application-uat.properties
application-prod.properties
spring.profiles.active=dev
================================================
Q) How to activate spring profile in runtime ?
================================================
================================================
Q) How to rollback transaction in data jpa ?
================================================
=> Using @Transactional annotation we can rollback tx when some exception occured
---------------------------------------------------------------
@Transactional(rollbackFor = Exception.class)
public void saveData() {
int i = 10/0;
addrRepo.save(addr);
----------------------------------------------------------------
=====================
Today's Assignment
=====================
Reference : youtube.com/watch?v=qe_NrRRsuVg
Reference : youtube.com/watch?v=mIFIb_JE47U
10) Develop data jpa application to insert emp record with addresses (one emp can
have multiple addresses like present and permanent)
11) Develop data jpa application to retrieve emp record along with addresses using
join query based on given emp id.