Commit c0c95e37 authored by Giridhari Sahoo's avatar Giridhari Sahoo

implemented DatabaseClient

parent ab33b427
...@@ -64,6 +64,15 @@ ...@@ -64,6 +64,15 @@
<artifactId>reactor-test</artifactId> <artifactId>reactor-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.nisum.Employeeinfo.config;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.r2dbc.core.DatabaseClient;
import javax.sql.DataSource;
import java.sql.Driver;
import static io.r2dbc.spi.ConnectionFactoryOptions.*;
@Configuration
public class DataSourceConfiguration {
private final Logger log = LoggerFactory.getLogger(DataSourceConfiguration.class);
public static final String POOL = "pool";
public static final String MYSQL = "mysql";
@Bean
public DataSource createDataSource(DataSourceProperties dataSourceProperties) {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/employeedb");
hikariConfig.setUsername("root");
hikariConfig.setPassword("root");
return new HikariDataSource(hikariConfig);
}
@Bean
public DataSourceTransactionManager createTransactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public ConnectionFactory createConnectionFactory(DataSourceProperties dataSourceProperties) {
return ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(DRIVER, POOL)
.option(PROTOCOL, MYSQL)
.option(HOST, dataSourceProperties.getHostName())
.option(PORT, dataSourceProperties.getPort())
.option(USER, dataSourceProperties.getUserName())
.option(PASSWORD, dataSourceProperties.getPassword())
.option(DATABASE, dataSourceProperties.getDatabaseName())
.build());
}
@Bean
public DatabaseClient createDataBaseClient(ConnectionFactory connectionFactory) {
return DatabaseClient.create(connectionFactory);
}
}
package com.nisum.Employeeinfo.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("spring.r2dbc")
public class DataSourceProperties {
private String driverClassName;
private String hostName;
private Integer port;
private String databaseName;
private String url;
private String userName;
private String password;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "DataSourceProperties{" +
"driverClassName='" + driverClassName + '\'' +
", hostName='" + hostName + '\'' +
", port=" + port +
", databaseName='" + databaseName + '\'' +
", url='" + url + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
...@@ -4,7 +4,6 @@ import com.nisum.Employeeinfo.dto.EmployeeDto; ...@@ -4,7 +4,6 @@ import com.nisum.Employeeinfo.dto.EmployeeDto;
import com.nisum.Employeeinfo.mapper.EmployeeMapper; import com.nisum.Employeeinfo.mapper.EmployeeMapper;
import com.nisum.Employeeinfo.model.Employee; import com.nisum.Employeeinfo.model.Employee;
import com.nisum.Employeeinfo.service.EmployeeService; import com.nisum.Employeeinfo.service.EmployeeService;
import com.nisum.Employeeinfo.service.EmployeeServiceImpl;
import com.nisum.Employeeinfo.validator.CommonServiceValidator; import com.nisum.Employeeinfo.validator.CommonServiceValidator;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
......
package com.nisum.Employeeinfo.dao;
import com.nisum.Employeeinfo.errorcode.ApiErrorCode;
import com.nisum.Employeeinfo.exception.EmployeeNotFoundException;
import com.nisum.Employeeinfo.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Repository
public class EmployeeDao {
@Autowired
private DatabaseClient databaseClient;
public Mono<Employee> saveEmployee(Employee employee){
String query="INSERT INTO employee ( name, email, dept, sal) VALUES (:name, :email, :dept, :sal)";
return databaseClient.sql(query)
.bind("name",employee.getName())
.bind("email",employee.getEmail())
.bind("dept",employee.getDept())
.bind("sal",employee.getSal())
.fetch()
.rowsUpdated()
.flatMap(rows->{
if (rows>0){
return Mono.just(employee);
}else {
return Mono.error(new EmployeeNotFoundException(ApiErrorCode.EMPLOYEE_NOT_FOUND,"Employee Not Found"));
}
});
}
public Flux<Employee> findAllEmployee(){
String query="SELECT * FROM employee ";
return databaseClient.sql(query)
.map((row,metadata)-> new Employee(
row.get("id",Integer.class),
row.get("name", String.class),
row.get("email",String.class),
row.get("dept",String.class),
row.get("sal",Double.class)
))
.all();
}
public Mono<Employee> findEmployeeById(Integer id){
String query= "SELECT id,name,email,dept,sal FROM employee WHERE id = :id";
return databaseClient.sql(query)
.bind("id",id)
.map((row, metadata) -> new Employee(
row.get("id", Integer.class),
row.get("name", String.class),
row.get("email", String.class),
row.get("dept", String.class),
row.get("sal", Double.class)
))
.one();
}
public Mono<Employee> updateEmployee(Integer id,Employee employee){
String query = "UPDATE employee SET name = :name, email = :email, dept = :dept, sal = :sal WHERE id = :id";
return databaseClient
.sql(query)
.bind("id", id)
.bind("name", employee.getName())
.bind("email", employee.getEmail())
.bind("dept", employee.getDept())
.bind("sal", employee.getSal())
.fetch()
.rowsUpdated()
.flatMap(updatedRows -> {
if (updatedRows > 0) {
// Return the updated employee object if update is successful
return Mono.just(employee);
} else {
// Return an error if no rows were updated (e.g., employee not found)
return Mono.error(new RuntimeException("Employee with ID " + id + " not found"));
}
});
}
public Mono<Void> deleteEmployeeById(Integer id){
String query= "DELETE FROM employee WHERE id = :id ";
return databaseClient.sql(query)
.bind("id",id)
.fetch()
.rowsUpdated()
.flatMap(updateRow->{
if (updateRow>0){
return Mono.empty();
}else {
return Mono.error(new EmployeeNotFoundException(ApiErrorCode.EMPLOYEE_NOT_FOUND,"Employee_Not_Found"));
}
});
}
}
...@@ -19,6 +19,16 @@ public class Employee { ...@@ -19,6 +19,16 @@ public class Employee {
@Column("sal") @Column("sal")
private Double sal; private Double sal;
public Employee() {
}
public Employee(Integer id, String name, String email, String dept, Double sal) {
this.id = id;
this.name = name;
this.email = email;
this.dept = dept;
this.sal = sal;
}
public Integer getId() { public Integer getId() {
return id; return id;
...@@ -61,4 +71,15 @@ public class Employee { ...@@ -61,4 +71,15 @@ public class Employee {
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", dept='" + dept + '\'' +
", sal=" + sal +
'}';
}
} }
...@@ -4,6 +4,6 @@ import com.nisum.Employeeinfo.model.Employee; ...@@ -4,6 +4,6 @@ import com.nisum.Employeeinfo.model.Employee;
import org.springframework.data.repository.reactive.ReactiveCrudRepository; import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends ReactiveCrudRepository<Employee,Integer> { //public interface EmployeeRepository extends ReactiveCrudRepository<Employee,Integer> {
} //}
package com.nisum.Employeeinfo.service; package com.nisum.Employeeinfo.service;
import com.nisum.Employeeinfo.dao.EmployeeDao;
import com.nisum.Employeeinfo.dto.EmployeeDto; import com.nisum.Employeeinfo.dto.EmployeeDto;
import com.nisum.Employeeinfo.mapper.EmployeeMapper; import com.nisum.Employeeinfo.mapper.EmployeeMapper;
import com.nisum.Employeeinfo.model.Employee; import com.nisum.Employeeinfo.model.Employee;
import com.nisum.Employeeinfo.repository.EmployeeRepository; //import com.nisum.Employeeinfo.repository.EmployeeRepository;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -14,8 +15,11 @@ import reactor.core.publisher.Mono; ...@@ -14,8 +15,11 @@ import reactor.core.publisher.Mono;
@Service @Service
public class EmployeeServiceImpl implements EmployeeService{ public class EmployeeServiceImpl implements EmployeeService{
// @Autowired
// private EmployeeRepository repository;
@Autowired @Autowired
private EmployeeRepository repository; private EmployeeDao dao;
private static final Logger log= LoggerFactory.getLogger(EmployeeServiceImpl.class); private static final Logger log= LoggerFactory.getLogger(EmployeeServiceImpl.class);
...@@ -24,13 +28,13 @@ public class EmployeeServiceImpl implements EmployeeService{ ...@@ -24,13 +28,13 @@ public class EmployeeServiceImpl implements EmployeeService{
return mono return mono
.doOnNext(dto->log.info("received employee dto {}",dto)) .doOnNext(dto->log.info("received employee dto {}",dto))
.map(EmployeeMapper::toEntity) .map(EmployeeMapper::toEntity)
.flatMap(employee -> repository.save(employee)) .flatMap(employee -> dao.saveEmployee(employee))
.doOnNext(employee -> log.info("employee saved successfully {}",employee)); .doOnNext(employee -> log.info("employee saved successfully {}",employee));
} }
@Override @Override
public Flux<Employee> getAllEmployee() { public Flux<Employee> getAllEmployee() {
return repository.findAll() return dao.findAllEmployee()
.doOnNext(employee -> log.info("processing all the employees {}",employee)) .doOnNext(employee -> log.info("processing all the employees {}",employee))
.doOnError(err->log.error("error occurred during fetching the employees {}",err.getMessage(),err)); .doOnError(err->log.error("error occurred during fetching the employees {}",err.getMessage(),err));
} }
...@@ -38,21 +42,21 @@ public class EmployeeServiceImpl implements EmployeeService{ ...@@ -38,21 +42,21 @@ public class EmployeeServiceImpl implements EmployeeService{
@Override @Override
public Mono<Employee> getEmployeeById(Integer id) { public Mono<Employee> getEmployeeById(Integer id) {
return repository.findById(id) return dao.findEmployeeById(id)
.doOnSuccess(employee -> log.info("fin")); .doOnSuccess(employee -> log.info("fin"));
} }
@Override @Override
public Mono<Employee> updateEmployee(Integer id, Mono<EmployeeDto> updatedEmployeeMono) { public Mono<Employee> updateEmployee(Integer id, Mono<EmployeeDto> updatedEmployeeMono) {
return repository.findById(id) return dao.findEmployeeById(id)
.flatMap(employee -> updatedEmployeeMono.flatMap(updatedEmployee->{ .flatMap(employee -> updatedEmployeeMono.flatMap(updatedEmployee->{
employee.setId(id); employee.setId(id);
employee.setName(updatedEmployee.getName()); employee.setName(updatedEmployee.getName());
employee.setDept(updatedEmployee.getDept()); employee.setDept(updatedEmployee.getDept());
employee.setEmail(updatedEmployee.getEmail()); employee.setEmail(updatedEmployee.getEmail());
employee.setSal(updatedEmployee.getSal()); employee.setSal(updatedEmployee.getSal());
return repository.save(employee); return dao.saveEmployee(employee);
})) }))
.switchIfEmpty(Mono.error(new RuntimeException("Employee Not Found"))); .switchIfEmpty(Mono.error(new RuntimeException("Employee Not Found")));
...@@ -61,7 +65,7 @@ public class EmployeeServiceImpl implements EmployeeService{ ...@@ -61,7 +65,7 @@ public class EmployeeServiceImpl implements EmployeeService{
@Override @Override
public Mono<Void> deleteEmployee(Integer id) { public Mono<Void> deleteEmployee(Integer id) {
return repository.deleteById(id) return dao.deleteEmployeeById(id)
.doOnSuccess(success -> log.info("employee deleted successfully")) .doOnSuccess(success -> log.info("employee deleted successfully"))
.doOnError(error -> log.error("Employee Not Found")); .doOnError(error -> log.error("Employee Not Found"));
} }
......
spring.application.name=Employeeinfo spring.application.name=Employeeinfo
spring.r2dbc.url=r2dbc:mysql://localhost:3306/employeedb #spring.r2dbc.url=r2dbc:mysql://localhost:3306/employeedb
spring.r2dbc.username=root #spring.r2dbc.username=root
spring.r2dbc.password=root #spring.r2dbc.password=root
spring.r2dbc.show-sql=true #spring.r2dbc.show-sql=true
spring:
r2dbc:
driverClassName: mysql
hostName: localhost
port: 3306
databaseName: employeedb
url: r2dbc:mysql://localhost:3306/employeedb
username: root
password: root
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment