Friday, 14 September 2018

SpringBoot restApi With Derby database

Tools & Techniques used:
Java
Maven
SpringBoot
RestApi 
Derby database

Derby is a full JDBC database, It can be used as a standalone database need not to be installed. Just need to point to an empty folder where it will create the data files. unlike in-memory database, the data can be persisted to the files.

The example illustrates the creation of an entity "user" and saves the data in the "users" table in derby.
crud operations: user:  add, edit, serachById, del, hard-delete are demonstrated through rest APIs.  

pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.13.1.1</version>
</dependency>

application.properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true

JpaConfig.java    custom class to configure the data source
import javax.sql.DataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JpaConfig {
        // primary Springboot datasource will be overwritten.
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url("jdbc:derby:/Database/Derby/DB-Data;create=true");
                //the database will be created at path c:/Database/Derby/DB-Data in windows
                //bydefault userid/password are not required by derby though can be provided.
return dataSourceBuilder.build();
}
}
Entity class User.java 

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@Column(name = "id")
int id;
@Column(name = "userid")
String userid;
@Column(name = "password")
String password;
@Column(name = "role")
String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.letUsLearn.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}

UserService.java
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.letUsLearn.entity.User;
import com.letUsLearn.repositiry.UserRepository;

@Service
public class UserService {

@Autowired
UserRepository repository;

public User getUserById(int id) {
return repository.findById(id).get();
}

public User findById(int id) {
return repository.findById(id).get();
}

public List<User> findAll() {
return repository.findAll();
}

public User addUser(User user) {
return repository.save(user);
}

public User inactiveUser(int id) {
User user = getUserById(id);
if (user != null) {
user.setRole(null);
return repository.save(user);
}
return null;
}

public String delete(int id) {
User user = getUserById(id);
if (user != null) {
repository.delete(user);
return "deleted";
}
return "record not found";
}
}

UserControler,java  
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import com.letUsLearn.entity.User;
import com.letUsLearn.service.UserService;

@RestController
@RequestMapping("/user")
public class UserControler {
@Autowired
UserService service;

@RequestMapping(method = RequestMethod.GET, path = "/hello")
public String hello() {
return "hello:";
}

@RequestMapping(method = RequestMethod.GET, path = "/{id}")
public User getUserById(@PathVariable(value = "id") int id) {
try {
return service.findById(id);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}

@RequestMapping(method = RequestMethod.GET, path = "/list")
public List<User> getAllUsers() {
try {
return service.findAll();
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}

@RequestMapping(method = RequestMethod.POST, path = "/add")
public User addUser(@RequestBody User user) {
try {
return service.addUser(user);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}

@RequestMapping(method = RequestMethod.GET, path = "/del/{id}")
public User inactiveUser(@PathVariable(value = "id") int id) {
try {
return service.inactiveUser(id);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.GET, path = "/del/{id}/hard")
public String delete(@PathVariable(value = "id") int id) {
try {
return service.delete(id);
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
}
}


the following JSON can be stored in a file and be imported to the postman.
SpringBootDerby.postman_collection.json

{
"variables": [],
"info": {
"name": "SpringBootDerby",
"_postman_id": "f5141a18-6b92-b381-7f0a-b76b237fb305",
"description": "",
"schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
},
"item": [
{
"name": "http://localhost:8080/user/add 1st admin",
"request": {
"url": "http://localhost:8080/user/add",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\r\n\t\"id\":\"1\",\r\n\t\"userid\":\"admin1\",\r\n\t\"password\":\"@#$\",\r\n\t\"role\":\"admin\"\r\n}"
},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/add 2nd admin",
"request": {
"url": "http://localhost:8080/user/add",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\r\n\t\"id\":\"2\",\r\n\t\"userid\":\"admin2\",\r\n\t\"password\":\"@#$\",\r\n\t\"role\":\"admin\"\r\n}"
},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/add 1st Editor",
"request": {
"url": "http://localhost:8080/user/add",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\r\n\t\"id\":\"3\",\r\n\t\"userid\":\"editor1\",\r\n\t\"password\":\"@#$\",\r\n\t\"role\":\"editor\"\r\n}"
},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/add 2nd Editor",
"request": {
"url": "http://localhost:8080/user/add",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\r\n\t\"id\":\"4\",\r\n\t\"userid\":\"editor2\",\r\n\t\"password\":\"@#$\",\r\n\t\"role\":\"editor\"\r\n}"
},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/add 3rd Editor",
"request": {
"url": "http://localhost:8080/user/add",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\r\n\t\"id\":\"5\",\r\n\t\"userid\":\"editor3\",\r\n\t\"password\":\"@#$\",\r\n\t\"role\":\"editor\"\r\n}"
},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/1",
"request": {
"url": "http://localhost:8080/user/1",
"method": "GET",
"header": [],
"body": {},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user",
"request": {
"url": "http://localhost:8080/user/list",
"method": "GET",
"header": [],
"body": {},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/del/5",
"request": {
"url": "http://localhost:8080/user/del/5",
"method": "GET",
"header": [],
"body": {},
"description": ""
},
"response": []
},
{
"name": "http://localhost:8080/user/del/5/hard",
"request": {
"url": "http://localhost:8080/user/del/5/hard",
"method": "GET",
"header": [],
"body": {},
"description": ""
},
"response": []
}
]
}

No comments:

Post a Comment