0% found this document useful (0 votes)
109 views4 pages

SBMs

The document discusses Spring Boot and microservices. It covers custom generators in Spring Data JPA that can be used to generate primary keys. An example is provided of implementing a custom generator class to generate primary keys for an entity.

Uploaded by

rmaharana328
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views4 pages

SBMs

The document discusses Spring Boot and microservices. It covers custom generators in Spring Data JPA that can be used to generate primary keys. An example is provided of implementing a custom generator class to generate primary keys for an entity.

Uploaded by

rmaharana328
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Date : 31-01-2023

Spring Boot and Microservices


6AM | Mr. Raghu | (ASHOK IT)
---------------------------------------------------------------------
Ref:
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Spring Boot Data JPA


Generators:- It creates/generates on PK value on save[INSERT] operations.

Ex PK: Pan card Number, Tx Number, Ref Number, Order Id ..etc

*) Generators are internally class.

1. Pre-Defined Generator
2. Custom Generator**

=> Hibernate, has provided @GeneratedValue with enum : GenerationType


it has possible values like:
SEQUENCE: If DB supports, it uses Database Sequence Concept to generate PK
IDENTITY: Check at DB, what concept does it uses to generate PK
[Auto-Increment]
TABLE: Stores PK value inside a table, nextPK= prevPK+1
AUTO : Choose one of matching type from above list.

=> All are Integer type, all works based on +1/+step concept.
=> If we use Generators then manual input for PK is ignored.
=> Incase of MySQL, Auto_Increment type column is created for PK
if we use IDENTITY.

=> Some DBs May not support sequence concept (Oracle supports)
In that case it internally moved to TABLE concept.

Ex:
create sequence hibernate_sequence
start 10
step 5;

select hibernate_sequence.nextval from dual;

=> 1st row in DB --> 10 PK


=> 2nd row in DB --> 15 PK
===============================================================
GenerationType.AUTO: Type is selected at runtime based on DB used.
-------------------------------------------------------------------

*) Custom Generator:
We can define our own PK value generation logic,
using below steps:
1. Define one class that implements IdentifierGenerator
2. override method generate()
3. Define Logic inside generate() method
4. At Entity class
-> use @GenericGenerator annotation
-> provide strategy="FullGeneratorClassName"
-> link with @GeneratedValue value (name==generator)

===code==================
1. Entity class
package com.app.raghu.entity;

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

import org.hibernate.annotations.GenericGenerator;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="emptab")
public class Employee {

//@GeneratedValue(strategy = GenerationType.AUTO)
//private Integer empId;

@Id
@GeneratedValue(generator = "testgen")
@GenericGenerator(name = "testgen",
strategy = "com.app.raghu.generator.MyCustGen")
@Column(name="eid")
private String empId;

@Column(name="ename")
private String empName;

@Column(name="esal")
private Double empSal;

@Column(name="edept")
private String empDept;

2. Custom generator class


package com.app.raghu.generator;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

public class MyCustGen implements IdentifierGenerator {

@Override
public Serializable generate(SharedSessionContractImplementor session, Object
object) throws HibernateException {

SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy");


String dte = sdf.format(new Date());
int rand = Math.abs(new Random().nextInt());

return "EMP:" + dte + "-" + rand;


}
}

3. Repository interface
package com.app.raghu.repo;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.raghu.entity.Employee;

public interface EmployeeRepository


extends JpaRepository<Employee, Integer>{

4. Runner class
package com.app.raghu.runner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.app.raghu.entity.Employee;
import com.app.raghu.repo.EmployeeRepository;

@Component
public class TestQueryRunner implements CommandLineRunner {

@Autowired
private EmployeeRepository repo;

public void run(String... args) throws Exception {


Employee e = new Employee();
e.setEmpDept("DEV");
e.setEmpName("AJAY");
e.setEmpSal(300.0);
repo.save(e);
}
}

5. application.properties
#Connection Properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/boot6am
spring.datasource.username=root
spring.datasource.password=root

#ORM Properties
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

==========MySQL Console ============


mysql> use boot6am;
Database changed

mysql> show tables;


+-------------------+
| Tables_in_boot6am |
+-------------------+
| booktab |
| depttab |
| emptab |
| prodtab |
+-------------------+
4 rows in set (0.00 sec)

mysql> select * from emptab;


+-----+-------+-------+------+
| eid | edept | ename | esal |
+-----+-------+-------+------+
| 1 | DEV | AB | 300 |
+-----+-------+-------+------+
1 row in set (0.00 sec)

mysql> desc emptab;


+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| eid | int | NO | PRI | NULL | auto_increment |
| edept | varchar(255) | YES | | NULL | |
| ename | varchar(255) | YES | | NULL | |
| esal | double | YES | | NULL | |
+-------+--------------+------+-----+---------+----------------+
4 rows in set (0.04 sec)

mysql> desc emptab;


+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| eid | varchar(255) | NO | PRI | NULL | |
| edept | varchar(255) | YES | | NULL | |
| ename | varchar(255) | YES | | NULL | |
| esal | double | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.01 sec)

mysql> select * from emptab;


+----------------------+-------+-------+------+
| eid | edept | ename | esal |
+----------------------+-------+-------+------+
| EMP:310123-133284456 | DEV | AJAY | 300 |
+----------------------+-------+-------+------+
1 row in set (0.00 sec)

You might also like